1

Can someone help me with parsing json string to object, I´m trying but always get error like this:

Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 3 path $[0]

Here is my code:

Item class:

@JsonInclude(JsonInclude.Include.NON_NULL)
public class Item{

    @JsonProperty("id")
    String id;
    
    @JsonProperty("dTime")
    long dTime;
    
    @JsonProperty("aTime")
    long aTime;
}

converting json to object:

String jsonString = "[
    [
        {
            "id":"string",
            "dTime": 1111111111,
            "aTime": 1111111111
        },
        {
            "id":"string",
            "dTime": 1111111111,
            "aTime": 1111111111
        }
    ]
]";
Gson gson = new Gson();
Type listType = new TypeToken<List<Item>>() {}.getType();
List<Item> list = gson.fromJson(jsonString, listType);

System.out.println(gson.toJson(list));

Update: Because i get this json as response from external API:

ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, request, String.class);

Is it possible to make this converting to Array of Item objects inside this restTemplate.exchange(..) or this with gson is better way?

3
  • 1
    The input JSON string contains duplicate list/array. You could either fix the type of the parsed object to be List<List<Item>> or strip the extra pair of [ and ]: jsonString.substring(1, jsonString.length() - 1) Commented Oct 26, 2020 at 8:30
  • Yes, you have two objects within an array within an array. According to the JSON you have, it should be List<List<Item>>. Commented Oct 26, 2020 at 8:37
  • 1
    The answer by Eklavya provides better handling of the response - it transforms the string returned by the external API into List<List<Item>> immediately, without extra manual parsing with Gson Commented Oct 26, 2020 at 9:01

2 Answers 2

1

You can use ParameterizedTypeReference to directly map in java list object and use List<List<Item>> since your data wrap in []

ParameterizedTypeReference<List<List<Item>>> responseType =
                    new ParameterizedTypeReference<List<List<Item>>>() {};
ResponseEntity<List<List<Item>>> response = 
                    restTemplate.exchange(url, HttpMethod.POST, request, responseType);
Sign up to request clarification or add additional context in comments.

Comments

0

Your jsonString has an extra '['. It should be

String jsonString = "
[
    {
        "id":"string",
        "dTime": 1111111111,
        "aTime": 1111111111
    },
    {
        "id":"string",
        "dTime": 1111111111,
        "aTime": 1111111111
    }
]
";

Comments

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.