I tried the below code to generate json
public void GenJson(){
HostDetails hostDetails = new HostDetails();
hostDetails.status = true;
hostDetails.deviceAddedTime = "2018-02-07 05:44:21.196541";
hostDetails.hostname = "MyHost";
hostDetails.id = 1;
Gson gson = new GsonBuilder().serializeNulls().create();
JsonElement je = gson.toJsonTree(hostDetails);
JsonObject jo = new JsonObject();
jo.add(hostDetails.getClass().getSimpleName(), je);
String jstr = jo.toString();
System.out.println(jstr);
}
class HostDetails {
public boolean status;
public String deviceAddedTime;
public String hostname;
public int id;
}
Generated Json output is
{
"HostDetails":{
"deviceAddedTime":"2018-02-07 05:44:21.196541",
"hostname":"MyHost",
"status":true,
"id":1
}
}
I want to convert above json data to class using Gson. Below code i tried. While debugging member of hostDetails1 class returns null. How can i solve
public void GenClass(){
Gson gson1 = new GsonBuilder().serializeNulls().create();
HostDetails hostDetails1 = gson1.fromJson(jstr, HostDetails.class);
}