0

我有以下 JSON,我想使用 Jackson JSON 处理器库 ( http://jackson.codehaus.org/ ) 解析它:

{
    "wrapper":{
        "general":{
            "value":10
        },
        "items":{
            "DOG":{
                "0":78,
                "1":125
                "name":"Lucky",
                "features":{
                    "color":"brown",
                    "sex":"male"
                }
            },
            "CAT":{
                "0":123,
                "1":94
                "name":"Fluffy",
                "features":{
                    "color":"black",
                    "sex":"female"
                }
            },
            "MOUSE":{
                "0":23,
                "1":33
                "name":"Jerry",
                "features":{
                    "color":"gray",
                    "sex":"male"
                }
            }
        }
    }
}

就最佳实践而言,您如何建议成为最佳方式?

4

1 回答 1

1

解析 JSON 的简单快速的形式是创建一个带有注释的 bean,然后调用 Jackson。

有些像这样:

@JsonIgnoreProperties(ignoreUnknown = true)
public class YourClass {

@JsonProperty("wrapper")
public Wrapper wrapper;

@JsonIgnoreProperties(ignoreUnknown = true)
public static class Wrapper{
        @JsonProperty("Items")
        public ArrayList<Item> items = new ArrayList<Item>();
}


@JsonIgnoreProperties(ignoreUnknown = true)
public static class Item{
        @JsonProperty("name")
        public String name;
        ...
}

....

}

然后在您的 Activity/Thread/AsyncTask 中:

  public ObjectMapper mMapper;

  ...

  if (mMapper == null)
      mMapper = new ObjectMapper();
  YourClass yourClass = (YourClass) mMapper.readValue(stringJSON, YourClas.class);

重用 ObjectMapper 非常重要,因为实例化它非常昂贵

改进:如果你设置这个 JSON 可能会得到改进(bean 基于它)

{  
  "wrapper":{  
    "general":{
        "value":10
    },
    "items":[  
        "item":{      
            "name":"DOG",  
            "0":78,  
            "1":125
            "name":"Lucky",
            "features":{
                "color":"brown",
                "sex":"male"
            }
        },
        "item":{
            "name":"CAT",
            "0":123,
            "1":94
            "name":"Fluffy",
            "features":{
                "color":"black",
                "sex":"female"
            }
        }
    ]
}
于 2013-11-14T09:41:38.997 回答