0

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?

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

So, what you're telling me is.. I could construct an object matching the array of objects I want, plug it into gson and it'll work like magic?
Yup. GSON just throws out the cruft you don't need according to this documentation.
1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.