0

I know there have been a lot of questions on this topic already, but I'm stuck here and I'm sure it's something quite stupid.

I'm parsing a JSON Api that looks like this (renamed & simplified here):

{
"merchant": {
    "name": "TestCo",
    "id": 108
},
"category": [
    {
        "merchant_id": 108,
        "category_name": "Baby Supplies",
        "category_id": 57,
    },
    {
        "merchant_id": 108,
        "category_name": "Dining",
        "category_id": 59,
    }
]}

I have a wrapper class, defined as:

public class WrapperObject {
  public MerchantObject merchant;
  public List<CategoryObject> category;}

Both merchant & category are properly defined classes of their own. Then I try to deserialize like so:

collectionType = new TypeToken<List<WrapperObject>>() {}.getType();
List<WrapperObject> wrapperObject = new Gson().fromJson(response, collectionType);

This blows up, GSON reports back "This is not a JSON Array".

This worked perfectly right up until last week, when the API changed. The only difference in the JSON was that it used to look like this (note the extra wrapping array around the data):

[{
    "merchant": {
        "name": "TestCo",
        "id": 108
    },
    "category": [
        {
            "merchant_id": 108,
            "category_name": "Baby Supplies",
            "category_id": 57,
        },
        {
            "merchant_id": 108,
            "category_name": "Dining",
            "category_id": 59,
        }
    ]}]

How do I adjust my code to parse the new JSON? NB, I have no control over the JSON. Thanks!

1 Answer 1

1

The square brackets around the old response denote an array (of one element in this case). It looks like the new API returns just a wrapper object, not an array of wrapper objects. Does this work?

wrapperType = new TypeToken<WrapperObject>() {}.getType();
WrapperObject wrapperObject = new Gson().fromJson(response, wrapperType);
Sign up to request clarification or add additional context in comments.

1 Comment

Sure does! Thanks, I knew I was missing something incredibly stupid, just needed another set of eyes on it. Much appreciated!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.