需要自定义Gson反序列化,只需要单个元素JSON,即Object

时间:2014-03-14 23:08:21

标签: java json gson

我有:Json:

{
  "id" : "1",
  "name": "John",
  "id_client": "2",
  ...
 }

我的课程:

public class Person{
    private int id;
    private String name; 
    private Client client;
    ...
}

public class Client{
  private int id;
}

如何将id_client:" 2",反序列化为Client对象并设置id(CLient)?

1 个答案:

答案 0 :(得分:0)

    ...
    Map<String,Object> parsed = jsonParser.parse(jsonString);
    Person thePerson = new Person(parsed);
    ...    

public class Person {
    ...
    public Person(Map<String,Object> parsed) {
        id = Integer.getInteger(parsed.getString("id"));
        name = parsed.getString("name");
        int idClient = Integer.getInteger(parsed.getString("id_client"));
        client = new Client(idClient);
    }
    ...
}