-1

I've written a file JSON with the information that I need to use to create an array

This is the json that I'm using

[{
  "matr": [0,0],
  "room": "b",
  "door": true,
  "respawnPoint": false
},
{
  "matr": [0,1],
  "room": "b",
  "door": false,
  "respawnPoint": false
},...
]    

and this is how I try to de-serialize it with java

String path="src/main/resources/room.json";
            JsonReader reader= new JsonReader(new FileReader(path));
            SupportPosition[] a=new Gson().fromJson(path, 
SupportPosition[].class);    

but this error appears

 com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 1 path $    
llevias
  • 3
  • 1

2 Answers2

0

You are passing the file path as a parameter into the Gson constructor. You must pass the JsonReader object into the Gson constructor as a parameter.

JsonReader reader= new JsonReader(new FileReader(path));
        SupportPosition[] a=new Gson().fromJson(reader, SupportPosition[].class);

try this and let me know.

Guru
  • 192
  • 1
  • 2
  • 15
0

Parsing JSON array into java.util.List with Gson I think your question has already been answered in a different post. Take a look into it.

public class Human {

    String name;
    Integer age;

    //getters and setters
}

Main class is below :

public class Solution{
 public static void main(String[] args) {

        ObjectMapper mapper = new ObjectMapper();
        String json = "[{\"name\":\"Dummy\", \"age\":37}, {\"name\":\"Dummy2\", \"age\":38}]";

        try {

            // 1. convert JSON array to Array objects
            Human[] HumanObjects = mapper.readValue(json, Human[].class);

            System.out.println("JSON array to Array objects...");
            for (Human Human : HumanObjects) {
                System.out.println(Human);
            }

            // 2. convert JSON array to List of objects
            List<Human> ppl2 = Arrays.asList(mapper.readValue(json, Human[].class));

            System.out.println("\nJSON array to List of objects");
            ppl2.stream().forEach(x -> System.out.println(x));

            // 3. alternative
            List<Human> pp3 = mapper.readValue(json, new TypeReference<List<Human>>() {});

            System.out.println("\nAlternative...");
            pp3.stream().forEach(x -> System.out.println(x));

        } catch (Exceptoion e) {
            e.printStackTrace();
        }

    }
    }

Use need to import "Jackson". Probably add a Maven dependency. Let me know if it helps.