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\":
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" } }
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.