如何使用Gson解析下面的JSON?
现在我用:
private AttachChildDataModel parseSuccess(String content){
Gson gson = new Gson();
return gson.fromJson(content, AttachChildDataModel.class);
}
AttachChildDataModel
具有以下成员变量:
private Integer adultId;
private Integer childId;
private PlatformEnum platform;
private String regId;
private Date loginDate;
private Date logoutDate;
private ClientApp clientApp;
我想解析的Json字符串是:
{"log":
{
"childId":2,
"adultId":1,
"logoutDate":null,
"platform":"IPHONE",
"regId":null,
"loginDate":1325419200000,
"clientApp":"CHILD_APP"
}
}
当我将对象放入Spring ModelView时,我将其添加到名称log
下。有问题的是当我尝试用Gson解析它时。现在,我用String#substring
手动删除“log”前缀和“}”后缀,但我认为有更好的解决方案。
答案 0 :(得分:0)
要解决您的问题,只需创建一个“foo”类,如下所示:
package stackoverflow.questions.q15614008;
public class Foo {
public AttachChildDataModel log;
}
并将其用作在Gson中解析的基类:
package stackoverflow.questions.q15614008;
import com.google.gson.*;
public class Q15614008 {
public static void main(String[] arg) {
String testString = "{\"log\": "
+ " {"
+ "\"childId\":2," + "\"adultId\":1,"
+ "\"logoutDate\":null,"
+ "\"platform\":\"IPHONE\","
+ "\"regId\":null,"
+ "\"loginDate\":1325419200000,"
+ "\"clientApp\":\"CHILD_APP\"}"
+ "}";
Gson gson = new Gson();
Foo foo = gson.fromJson(
testString, Foo.class);
System.out.println("Result: " + foo.log.toString());
}
}
然后只使用log
类的Foo
成员变量。