1

如何使用 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 时,我将其添加到 name 下log。有问题的是当我尝试用 Gson 解析它时。现在,我用 手动删除“log”前缀和“}”后缀String#substring,但我认为有更好的解决方案。

4

1 回答 1

0

To solve your problem, just create a "foo" class like this:

package stackoverflow.questions.q15614008;

public class Foo {

   public AttachChildDataModel log;

}

and use it as base class for parsing in 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());
  }

}

Then use only the log member variable of the Foo class.

于 2013-08-30T20:22:13.303 回答