0

I am trying to convert a JSON array to a Java object, but I am having problems understanding how to use GSON.

The JSON array looks like this:

"[
  {
    "category": "1",
    "checks": [
      {
        "check": "1.1",
        "penaltypoints": "1.1",
        "keypoint": "1.1"
      },
      {
        "check": "1.2",
        "penaltypoints": "1.2",
        "keypoint": "1.2"
      }
    ]
  },
  {
    "category": "2",
    "checks": [
      {
        "check": "2.1",
        "penaltypoints": "2.1",
        "keypoint": "2.1"
      },
      {
        "check": "2.2",
        "penaltypoints": "2.2",
        "keypoint": "2.2"
      }
    ]
  }
]"

My corresponding Java classes are:

class Category {
    public String description;
    public List<Check> checks;
}

class Check {
    public String description;
    public float penaltyPoints;
    public KeyPoint keypoint;
}

class KeyPoint {
    public String description;
}

And this is how I called GSON:

Gson gson = new Gson();         
Category categoriesArray[] = gson.fromJson(jsonString, Category[].class);

At the moment it is throwing up the following error:

Expected BEGIN_OBJECT but was STRING at line 1 column 125

I am new to GSON and am having problems understanding how it works. Can anyone please help me understand what I am doing wrong?

1 Answer 1

3

You're expecting this

    "keypoint": "2.1"

to be mapped to

public KeyPoint keypoint;
...
class KeyPoint {
    public String description;
}

In Java-JSON conversions, a POJO is meant to map to a JSON object and vice versa. Here, you're trying to map a JSON String to a POJO. That won't work by by default.

Either write and register your own TypeAdapter with Gson that will do this conversion or change your JSON to

"keypoint" : {
     "description" : "2.1"
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, it seems that was the problem. I had it mapped differently in my mind! I will accept your answer when the timer lets me :).

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.