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?

Jonas
  • 121,568
  • 97
  • 310
  • 388
Avnish
  • 81
  • 1
  • 2
  • 6

2 Answers2

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" } }
Jonas
  • 121,568
  • 97
  • 310
  • 388
  • 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 – Avnish Aug 02 '11 at 11:36
  • 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... – Avnish Aug 02 '11 at 11:39
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.

Miserable Variable
  • 28,432
  • 15
  • 72
  • 133