Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Gson and JsonObject to format and parse data

Tags:

json

parsing

gson

I am using JsonObject and Gson to format the data i need to send in the form of String and then retrieve and parse it somewhere else. This is my simple code which is not working:

public static void main(String[] args) 
{

    Gson g = new Gson();
    Gson listG = new Gson();
    ArrayList<String> l= new ArrayList<String>();
    l.add("abcd");
    l.add("efgh");
    l.add("ijkl");

    String list = listG.toJson(l);

    JsonObject jObject = new JsonObject();
    jObject.addProperty("command" , 1);
    jObject.addProperty("message" , "this is a test message");
    jObject.addProperty("list" , list);

    String toSend = g.toJson(jObject);
    System.out.println(toSend);  

    Gson rec = new Gson();
    JsonObject newObj = rec.fromJson(toSend, JsonObject.class);
    System.out.println(newObj);  // getting nothing in newObj


}

What am i doing wrong here?

like image 425
Jazib Avatar asked Nov 17 '12 21:11

Jazib


People also ask

What is JSON object parse?

JSON parsing is the process of converting a JSON object in text format to a Javascript object that can be used inside a program. In Javascript, the standard way to do this is by using the method JSON. parse() , as the Javascript standard specifies.

Can we convert JSON object to String?

Use the JavaScript function JSON.stringify() to convert it into a string. const myJSON = JSON.stringify(obj); The result will be a string following the JSON notation.

What is the difference between JSON and GSON?

The JSON format was originally specified by Douglas Crockford. On the other hand, GSON is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object.


1 Answers

You should use:

JsonObject newObj = new JsonParser().parse(toSend).getAsJsonObject();

Lots of calls in there, but the gist is to use the JsonParser class.

like image 125
NG. Avatar answered Sep 17 '22 01:09

NG.