0

i'm having a problem with GSON, i'm trying to get a json file and transform them into a list of objects, i have no idea how to solve that, i tried to follow the article below but im recieving this error message below.

article: https://attacomsian.com/blog/gson-read-json-file

test.json

[
{ 
  "code": "sasdsa321", 
  "items": [
    {
      "id":"1", 
      "name":"item1"
    },
    {
      "id":"2", 
      "name":"item2"
    },
    ...
  ]
},
...
]

my code

Gson gson = new Gson();

// create a reader
Reader reader = Files.newBufferedReader(Paths.get("test.json"));

// convert JSON array to list of items
List<Item> items= new Gson().fromJson(reader, new TypeToken<List<Item>>() {}.getType());

// print users
items.forEach(System.out::println);

Error message

"com.google.gson.stream.MalformedJsonException: Expected value at line 1 column 1 path $"
Chaosfire
  • 4,818
  • 4
  • 8
  • 23
  • 1
    Judging by json, you do not represent its' structure correctly, you have a list of some objects, each of which has a list of items. You are trying to deserialize directly into list of items. – Chaosfire Jun 07 '22 at 11:58
  • Even then, i can't reproduce your exception. Even though the objects are empty, because of the structural mismatch, deserialization finishes successfully. – Chaosfire Jun 07 '22 at 12:00
  • The object "Item" reproduces exactly what the json have, talking about a List of Objects, What its the right way to do or can i do using other library instead of GSON ? – Guilherme Gonzalez Jun 07 '22 at 14:46
  • As i said, the error is not reproducible with the json you provided. This [question](https://stackoverflow.com/questions/11484353/gson-throws-malformedjsonexception) might be of help in fixing it. – Chaosfire Jun 07 '22 at 15:05

0 Answers0