简体   繁体   English

用jackson嵌套json解析android

[英]nested json parsing for android with jackson

i just started to android prograamming and found nice tutorial by using imdb api. 我刚开始使用android程序编程,并使用imdb api找到了很好的教程。 instead of using xml in this tutorial i would like to use json and for the recevied json i have a problem. 而不是在本教程中使用xml我想使用json和接收的json我有一个问题。 this is the person.json: 这是person.json:

    [
        {
    "score":1,
    "popularity":3,
    "name":"Brad Pitt",
    "id":287,
    "biography":"test",
    "url":"http://www.themoviedb.org/person/287",
    "profile":[
        {
            "image":{
                "type":"profile",
                "size":"thumb",
                "height":68,
                "width":45,
                "url":"http://d3gtl9l2a4fn1j.cloudfront.net/t/p/w45/w8zJQuN7tzlm6FY9mfGKihxp3Cb.jpg",
                "id":"4ea5cb8c2c0588394800006f"
            }
        },
        {
            "image":{
                "type":"profile",
                "size":"profile",
                "height":281,
                "width":185,
                "url":"http://d3gtl9l2a4fn1j.cloudfront.net/t/p/w185/w8zJQuN7tzlm6FY9mfGKihxp3Cb.jpg",
                "id":"4ea5cb8c2c0588394800006f"
            }
        },
        {
            "image":{
                "type":"profile",
                "size":"h632",
                "height":632,
                "width":416,
                "url":"http://d3gtl9l2a4fn1j.cloudfront.net/t/p/h632/w8zJQuN7tzlm6FY9mfGKihxp3Cb.jpg",
                "id":"4ea5cb8c2c0588394800006f"
            }
        },
        {
            "image":{
                "type":"profile",
                "size":"original",
                "height":1969,
                "width":1295,
                "url":"http://d3gtl9l2a4fn1j.cloudfront.net/t/p/original/w8zJQuN7tzlm6FY9mfGKihxp3Cb.jpg",
                "id":"4ea5cb8c2c0588394800006f"
            }
        }
    ],
    "version":685,
    "last_modified_at":"2013-02-16 07:11:15 UTC"
}
]

my two object for them: 我的两个对象:

    public class Person implements Serializable {

   private static final long serialVersionUID = 6794898677027141412L;

   public String score;
   public String popularity;
   public String name;
   public String id;
   public String biography;
   public String url;
   public String version;
   public String lastModifiedAt;
   public Profile profile;
    }

    public class Profile implements Serializable {

   private static final long serialVersionUID = -8735669377345509929L;

   public ArrayList<Image> imagesList;

    }

    public class Image implements Serializable {

   private static final long serialVersionUID = -2428562977284114465L;

   public String type;
   public String url;
   public String size;
   public int width;
   public int height;   
    }

ı couldnt figure out how to retrieve person list by using jackson object mapper. 我无法弄清楚如何使用杰克逊对象映射器检索人员列表。 when i use this one: 当我使用这个:

    ObjectMapper mapper = new ObjectMapper();
    Person person= mapper.readValue(jsonResponseString, Person.class);

i got: 我有:

02-16 18:34:48.010: W/System.err(376): com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of com.example.imdbsearcher.model.Person out of START_ARRAY token 02-16 18:34:48.180: W/System.err(376): at [Source: java.io.StringReader@40a81778; 02-16 18:34:48.010:W / System.err(376):com.fasterxml.jackson.databind.JsonMappingException:无法从START_ARRAY标记02-16 18反序列化com.example.imdbsearcher.model.Person的实例:34:48.180:W / System.err(376):at [来源:java.io.StringReader@40a81778; line: 1, column: 1] 02-16 18:34:48.554: W/System.err(376): at com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:599) 02-16 18:34:48.830: W/System.err(376): at com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:593) line:1,column:1] 02-16 18:34:48.554:W / System.err(376):at com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:599)02-16 18: 34:48.830:W / System.err(376):at com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:593)

i have changed the retrieve method with advice of Keith and crdnilfan. 我已经用Keith和crdnilfan的建议改变了检索方法。 but now i have a problem with the attribute of profile. 但现在我的配置文件属性有问题。

i realized that i am missing that one in person object and basicly i have created new profile object and moved imageList to this class. 我意识到我错过了一个人对象,基本上我创建了新的配置文件对象并将imageList移动​​到这个类。

i have updated POJO's as above. 我已经更新了POJO,如上所述。

but now i am getting the same error for the profile. 但现在我得到的配置文件错误相同。

Can not deserialize instance of com.example.imdbsearcher.model.Profile out of START_ARRAY token 无法从START_ARRAY令牌中反序列化com.example.imdbsearcher.model.Profile的实例

That's because you are trying to deserialize a list of Person.class, not one instance. 那是因为你试图反序列化Person.class列表,而不是一个实例。 Create another class like this 创建这样的另一个类

public class PersonList extends ArrayList<Person> {}

and then use 然后使用

ArrayList<Person> people = mapper.readValue(jsonResponseString, PersonList.class);

You need to deserialize the list, as your JSON is an array: 您需要反序列化列表,因为您的JSON是一个数组:

List<Person> people = mapper.readValue(
                      jsonResponseString, new TypeReference<List<Person >>(){});

However, after you do that you will have some additional deserialization errors because of the profile property in your JSON. 但是,执行此操作后,由于JSON中的配置文件属性,您将有一些额外的反序列化错误。 Checkout: http://jackson.codehaus.org/1.5.7/javadoc/org/codehaus/jackson/annotate/JsonIgnoreProperties.html 结帐: http//jackson.codehaus.org/1.5.7/javadoc/org/codehaus/jackson/annotate/JsonIgnoreProperties.html

Update: 更新:

public class Person implements Serializable 
{

  public List<Object> profile;

  public String score;
  public String popularity;
  public String name;
  public String id;
  public String biography;
  public String url;
  public String version;
  public String last_modified_at;
}

There are several ways to deal with this. 有几种方法可以解决这个问题。 This will give you a linked hash map for Profile. 这将为您提供Profile的链接哈希映射。

Alternatively, if you control the JSON format, change the profile syntax to this: 或者,如果您控制JSON格式,请将配置文件语法更改为:

"profile":[
      image:...,
      image:...
 ]

The other two answers clearly explain the reason for the error, it would get rid off the error and it will parse Person object. 另外两个答案清楚地解释了错误的原因,它将摆脱错误,它将解析Person对象。 But for me it failed to parse image objects. 但对我来说,它无法解析图像对象。 With below POJO we can parse the specified json completely, without any issues even in the absence of 使用下面的POJO,我们可以完全解析指定的json,即使没有任何问题也没有任何问题

@JsonIgnoreProperties

or 

mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);

POJO definition: POJO定义:

public  class PersonList extends ArrayList<Person> {}

public class Person implements Serializable {

    private static final long serialVersionUID = 6794898677027141412L;

    public String score;
    public String popularity;
    public String name;
    public String id;
    public String biography;
    public String url;
    public String version;
    @JsonProperty(value="last_modified_at")
    public String lastModifiedAt;

    public List<Profile> profile;

}

public class Profile implements Serializable {

private static final long serialVersionUID = -8735669377345509929L;
    @JsonProperty(value="image")
    public Image imagesList;

 }

public class Image implements Serializable {

    private static final long serialVersionUID = -2428562977284114465L;

    public String id;
    public String type;
    public String url;
    public String size;
    public int width;
    public int height;

}

This should parse the json 这应该解析json

String jsonResponseString = readJsonFile("person.json"); 
ObjectMapper mapper = new ObjectMapper();

PersonList person= mapper.readValue(jsonResponseString, PersonList.class);
       or
List<Person> person= mapper.readValue(jsonResponseString, 
new TypeReference<List< Person>>(){}); //if we use this we dont have to define PersonList class

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM