我尝试了以下代码来生成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;
}
生成的Json输出
{
"HostDetails":{
"deviceAddedTime":"2018-02-07 05:44:21.196541",
"hostname":"MyHost",
"status":true,
"id":1
}
}
我想使用Gson将上面的json数据转换为类。我尝试下面的代码。而hostDetails1类的调试成员返回 null 。我该如何解决
public void GenClass(){
Gson gson1 = new GsonBuilder().serializeNulls().create();
HostDetails hostDetails1 = gson1.fromJson(jstr, HostDetails.class);
}
答案 0 :(得分:3)
此行不是必需的。
jo.add(hostDetails.getClass().getSimpleName(), je);
jo
变量都不是。
您为JSON添加了一个额外的级别,您可以在一行中立即创建JSON字符串...
如果要生成正确的JSON字符串,请尝试
Gson gson = new GsonBuilder().serializeNulls().create();
String jstr = gson.toJSON(hostDetails);
System.out.println(jstr);
使用此行
gson1.fromJson(jstr, HostDetails.class);
Gson期待这个
{
"deviceAddedTime":"2018-02-07 05:44:21.196541",
"hostname":"MyHost",
"status":true,
"id":1
}
如果要解析给定的JSON,则需要另一个包装类
class Foo {
public Foo() {}
@SerializedName("HostDetails")
public HostDetails hostDetails;
}
然后
HostDetails hostDetails1 = gson1.fromJson(jstr, Foo.class).hostDetails;
你需要一个默认的无参数构造函数
class HostDetails {
public HostDetails() {}
public boolean status;
public String deviceAddedTime;
public String hostname;
public int id;
}
也许是一些二传手和吸气鬼。
答案 1 :(得分:0)
尝试getter/setters
,这种做法。
class HostResponse{
@SerializedName("HostDetails")
HostDetails hostDetails;
}
class HostDetails {
public boolean status;
public String deviceAddedTime;
public String hostname;
public int id;
}
HostResponse hostResponse= new Gson().fromJson(json.toString(), HostResponse.class);