Converting JsonNode to java array
Asked Answered
H

5

14

I am working on Play framewrok 2 with websocket and JsonNode . the front end is connected to the play framework backend by use of websocket. I converted a javascript array into a json node and sent it to the backend by the use of the webscoket connection. Now my problem is how do i convert the json object into a a java array or any suitable structure so that i can manipulate the data.

this is the json object I created

var myjeson = {"x":arrayX,"y":arrayY} ;

this is the array which is populated dynamically

 function pixelCount ()
    {  arrayX[counter] = xcoordinate;        
    arrayY[counter] = ycoordinate;
    socket.send(" from array X,Y  "+arrayX[counter]+ " " +arrayY[counter]); 
    ++counter;      
    }

the code below sends the data

$('button.send').click(function() {            
sock.send(JSON.stringify(myjeson)); 

on the server side i have the following code

 public static WebSocket<JsonNode> givenIn() {
    return new WebSocket<JsonNode>() {
    // called when the websocket is established
    public void onReady(WebSocket.In<JsonNode> in, WebSocket.Out<JsonNode> out) {
    // register a callback for processing instream events             
    in.onMessage(new Callback<JsonNode>() {
    public void invoke(JsonNode event) {                 
    Logger.info(event.toString());
    }

when I check the log the message is delivered : below is the log info [info] application -

{"x":
[78.72727298736572,79.72727298736572,82.72727298736572,
7298736572,93.72727298736572,83.72727298736572132.72727298736572],

"y":
[82.6363639831543,82.6363639831543,63.54545593261719,63.54545593261719,64.545455932
61719,65.54545593261719,70.54545593261719,189.5454559326172,188.5454559326172]}

Now I will like to place these data in an array so that I can access them. any suggestion will be appreciated.an alternative suggestion is also welcomed.

Hege answered 18/7, 2012 at 7:11 Comment(0)
N
1

The answer is mostly in the Jackson documentation and the tutorial;

you have several ways to transform that JsonNode into useful data.

If you know in advance the structure of the data you can use the Data Binding approach: for "full" binding make a Class corresponding to all fields); For a less structured approach the 'raw' binding let you use generic objects.

Otherwise the Tree Model approach should work for you; the example you will find in the linked page corresponds quite well to your use case.

Please try that example, then if you have more specific issues come back with the exact practical or phylosophical issues!

Nika answered 18/7, 2012 at 11:45 Comment(6)
thanks Stefano was able to implement the json node using the raw binding with generics. You made my Week!!!!!Hege
@faisalabdulai you are welcome :) If my answer was helpful don't forget to vote up / pick it as the good answer. If you have useful detailed feedback that you want to share, you can still vote my answer but add your own answer.Nika
If you are looking for code sample, here's the answer https://mcmap.net/q/168567/-deserializing-polymorphic-types-with-jackson-based-on-the-presence-of-a-unique-propertyWira
Downvote for passing lots of links and no quick solution. new ObjectMapper().convertValue(jsonNode, ArrayList.class)Meghanmeghann
@AlexBurdusel Please update your comment as answer. Thank you.Guyton
@JETHALAL added it as an answer now.Meghanmeghann
M
39

Moving my comment to an answer, as it got upvoted a lot.

This should do what the OP needed:

new ObjectMapper().convertValue(jsonNode, ArrayList.class)

Meghanmeghann answered 6/12, 2018 at 10:1 Comment(0)
J
3

A quick way to do this using the tree-model... convert the JSON string into a tree of JsonNode's:

ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readTree("...<JSON string>...");

Then extract the child nodes and convert them into lists:

List<Double> x = mapper.convertValue(rootNode.get("x"), ArrayList.class);
List<Double> y = mapper.convertValue(rootNode.get("y"), ArrayList.class);

A slight longer, but arguable better way to do this is to define a class representing the JSON structure you expect:

public class Request {
    List<Double> x;
    List<Double> y;
}

Then deserialized directly as follows:

Request request = mapper.readValue("...<JSON string>...", Request.class);
Jaconet answered 14/3, 2018 at 22:24 Comment(0)
A
2

"... how do I convert the json object into a java array"

import com.google.common.collect.Streams;

public void invoke(JsonNode event) {                 
    Streams.stream(event.withArray("x").elements())
        .forEach( num -> Logger.info(num.asDouble()) )
}

The trick is to first get the Iterator object using "elements()" method, then using Guava "stream" method get the stream. Once you have the stream you can do all kinds of array operations(e.g. filter, map) to consume your data.

Allure answered 30/11, 2018 at 14:1 Comment(0)
N
1

The answer is mostly in the Jackson documentation and the tutorial;

you have several ways to transform that JsonNode into useful data.

If you know in advance the structure of the data you can use the Data Binding approach: for "full" binding make a Class corresponding to all fields); For a less structured approach the 'raw' binding let you use generic objects.

Otherwise the Tree Model approach should work for you; the example you will find in the linked page corresponds quite well to your use case.

Please try that example, then if you have more specific issues come back with the exact practical or phylosophical issues!

Nika answered 18/7, 2012 at 11:45 Comment(6)
thanks Stefano was able to implement the json node using the raw binding with generics. You made my Week!!!!!Hege
@faisalabdulai you are welcome :) If my answer was helpful don't forget to vote up / pick it as the good answer. If you have useful detailed feedback that you want to share, you can still vote my answer but add your own answer.Nika
If you are looking for code sample, here's the answer https://mcmap.net/q/168567/-deserializing-polymorphic-types-with-jackson-based-on-the-presence-of-a-unique-propertyWira
Downvote for passing lots of links and no quick solution. new ObjectMapper().convertValue(jsonNode, ArrayList.class)Meghanmeghann
@AlexBurdusel Please update your comment as answer. Thank you.Guyton
@JETHALAL added it as an answer now.Meghanmeghann
U
1

Quick answer for the Tree Model approach mentioned by Stefano in the accepted answer:

JsonNode rootNode = new ObjectMapper().readTree(new StringReader(jsonStr));
JsonNode x=rootNode.get("x");
System.out.println(x.getNodeType());//should print: ARRAY
Iterator<JsonNode> arrayIterator=x.iterator();
List<Double> xList=new ArrayList<Double>();
while(arrayIterator.hasNext()) {
    JsonNode elementInX=arrayIterator.next();
    Double xDoubleValue=elementInX.asDouble();
    xList.add(xDoubleValue);
}
Double[] xArray=new Double[xList.size()];
xList.toArray(xArray);//xArray now should be what you want

//do the same thing to y
Ulterior answered 2/11, 2018 at 11:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.