简体   繁体   中英

(Java) Parsing JSON from file error

I have a file query.json that contains [["Rain"], ["Cloudy", "Sprinkler"], [false, true]] to represent a query for a Bayesian network.

String queryContents = readEntireFile(new File("query.json"));
Query query = Query.queryFromString(queryContents);

Is used to read the entire file and then call the method to create the query.

When I call my queryFromString(String s) method I get the error:

Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING

my queryFromString method is

    public static Query queryFromString(String s) { 
    Gson gson = new Gson();  
    JsonParser parser = new JsonParser();
    JsonArray jsonNodes = parser.parse(s).getAsJsonArray();
    JsonElement element = jsonNodes.get(0);
    JsonArray jsonNode = element.getAsJsonArray();
    String [] q = gson.fromJson(jsonNode.get(0), String[].class);
    String [] e = gson.fromJson(jsonNode.get(1), String[].class);
    boolean[] v = gson.fromJson(jsonNode.get(2), boolean[].class);



    return null;
    }

This is my first time using JSON, so I' not really sure why it is producing this error, any help?

Your root JSON value is a JSON array containing 3 other JSON values: two JSON arrays containing string values and a JSON array containing boolean values.

You should be operating on the root JSON array directly.

JsonArray jsonNodes = parser.parse(s).getAsJsonArray();
String[] q = gson.fromJson(jsonNodes.get(0), String[].class);
String[] e = gson.fromJson(jsonNodes.get(1), String[].class);
boolean[] v = gson.fromJson(jsonNodes.get(2), boolean[].class);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM