Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting JSON to Java object using Gson

I am trying to convert JSON string to simple java object but it is returning null. Below are the class details.

JSON String:

   {"menu": 
    {"id": "file",
     "value": "File",
     }
   }

This is parsable class:

public static void main(String[] args) {
try {
    Reader r = new
         InputStreamReader(TestGson.class.getResourceAsStream("testdata.json"), "UTF-8");
    String s = Helper.readAll(r);
    Gson gson = new Gson();
    Menu m = gson.fromJson(s, Menu.class);
    System.out.println(m.getId());
    System.out.println(m.getValue());
    } catch (IOException e) {
    e.printStackTrace();
    }
}

Below are th model class:

public class Menu {

    String id;
    String value;

    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getValue() {
        return value;
    }
    public void setValue(String value) {
        this.value = value;
    }

    public String toString() {
        return String.format("id: %s, value: %d", id, value);
    }

}

Everytime i am getting null. Can anyone please help me?

like image 593
Avnish Avatar asked Aug 01 '11 10:08

Avnish


People also ask

How do you convert JSON to Java object?

We can convert a JSON to Java Object using the readValue() method of ObjectMapper class, this method deserializes a JSON content from given JSON content String.

How does Gson from JSON work?

Gson can work with arbitrary Java objects including objects for which you do not have the source. For this purpose, Gson provides several built in serializers and deserializers. A serializer allows to convert a Json string to corresponding Java type. A deserializers allows to convert from Java to a JSON representation.

Why is Gson used?

GSON has been successfully used in several android apps that are in Google Play today. The benefit you get with GSON is that object mapping can save the time spent writing code.


1 Answers

Your JSON is an object with a field menu.

If you add the same in your Java it works:

class MenuWrapper {
    Menu menu;
    public Menu getMenu() { return menu; }
    public void setMenu(Menu m) { menu = m; }
}

And an example:

public static void main(String[] args) {
    String json =  "{\"menu\": {\"id\": \"file\", \"value\": \"File\"} }";

    Gson gson = new Gson();
    MenuWrapper m = gson.fromJson(json, MenuWrapper.class);
    System.out.println(m.getMenu().getId());
    System.out.println(m.getMenu().getValue());

}

It will print:

file
File

And your JSON: {"menu": {"id": "file", "value": "File", } } has an error, it has an extra comma. It should be:

{"menu": {"id": "file", "value": "File" } }
like image 85
Jonas Avatar answered Oct 13 '22 13:10

Jonas