开发者

Parsing this JSON with Java?

When Parsing JSON I normally just constuct an object and use the gsonlibrary to parse my String into that object.

However, I now find myself with a rather complex response which consists of many elements each with sub elements of objects and arrays and arrays of objects. It looks something like this...

{
 "type": "thetype",
 "object":{
   "text": "texthere",
   "moretext": "more here"
  },
  ...,
  ...,
  ...,
  ...,
  "fieldIwant": [
   {
    "object":"object!"
    },
   ....
   ....
   {
    "object":"object!"
    },
   ]
}

The thing is, I'm only really interested in fieldIwantand nothing else. Is there not a way in Java for me to just extract that field and work with it alone and not all this other dead weight I do not need?开发者_StackOverflow


According to this http://sites.google.com/site/gson/gson-design-document it looks like gson does this for you by default.

When you are deserializing a Json string into an object of desired type, you can either navigate the tree of the input, or the type tree of the desired type. Gson uses the latter approach of navigating the type of the target object. This keeps you in tight control of instantiating only the type of objects that you are expecting (essentially validating the input against the expected "schema"). By doing this, you also ignore any extra fields that the Json input has but were not expected.

In other words, it doesn't deserialize any of the fields you don't need. You should be good to go.


You can use the low level JsonParser API

JsonObject jsonObject = new JsonParser().parse(json).getAsJsonObject();
yourArray = new Gson().fromJson(jsonObject.get("fieldIwant"), yourArrayType);

Alternatively you can create an ExclusionStrategy to use with a GsonBuilder

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜