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?
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.
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.
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.
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" } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With