简体   繁体   中英

How to parse this JSON into java object?

http://pastebin.com/rXbeKqAa

Hi all I have been trying to parse the above JSON into a java program and store it into an object... (Don't have a specific structure at the moment, as long as I can get the data from the object.)

Have been trying to use GSON but I can't seem to get it right..

        String inputLine="";
    HttpClient httpclient= new DefaultHttpClient();
    HttpGet method = new HttpGet("http://localhost:3000/specs/215/errors.js");
    HttpResponse response =httpclient.execute(method);
    BufferedReader in = new BufferedReader(
            new InputStreamReader(
                    response.getEntity().getContent()));

    inputLine = in.readLine();
    System.out.println(inputLine);
    in.close();
    Gson gson = new Gson();
    JsonParser parser = new JsonParser();
    JsonArray array = parser.parse(inputLine).getAsJsonArray();

    for(int i=0; i < array.size(); i++) {

        Errors e = gson.fromJson(array.get(0), Errors.class);
        System.out.println(e.error.getReason());
    }

and the error i get is:

Exception in thread "main" java.lang.IllegalStateException: This is not a JSON Array.
    at com.google.gson.JsonElement.getAsJsonArray(JsonElement.java:99)
    at test.Getter.main(Getter.java:37)

Anyone please point me in the right direction? Thanks.

The JSON String is not a JSON Array String. JSON String starts and ends with { , } respectively while JSON Array starts and ends with [ , ] respectively.

This line is wrong:

JsonArray array = parser.parse(inputLine).getAsJsonArray();

Rather retrieve it as a JsonObject .

I fixed the issue I had. Novice mistake with the serialized annotations. For some reason I thought they would reference the name of the class not the field names. But more importantly, I also had to create a root-level container class to hold my classes. That allowed for all the objects to be parsed.

JSON Structures are realized as an object, record,struct, dictionary, hash table, keyed list, or associative array.

You can use eval() function to achieve the desired goal. I think this will help you/

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