6

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?

2

2 Answers 2

13

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" } }
Sign up to request clarification or add additional context in comments.

2 Comments

thanks, Jonas. But why did add Menu Wrraper class?...Do you have any document for this so that i can learn more...if u have please share it with me....thanks
As i am new to this. I wanted to know is there any in built GSON in java or android for this converting JSON to java or vice -versa...as i know only JACKSON and GSON...please help me thanks...
1

What I have found helpful with Gson is to create an an instance of the class, call toJson() on it and compare the generated string with the string I am trying to parse.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.