简体   繁体   English

如何将此JSON解析为Java对象?

[英]How to parse this JSON into java object?

http://pastebin.com/rXbeKqAa 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.) 大家好,我一直在尝试将上述JSON解析为Java程序并将其存储到对象中……(目前我没有特定的结构,只要我可以从对象中获取数据即可。)

Have been trying to use GSON but I can't seem to get it right.. 一直在尝试使用GSON,但我似乎无法正确使用它。

        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字符串不是JSON数组字符串。 JSON String starts and ends with { , } respectively while JSON Array starts and ends with [ , ] respectively. JSON字符串分别以{}开头和结尾,而JSON Array分别以[]开头和结尾。

This line is wrong: 这行是错误的:

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

Rather retrieve it as a JsonObject . 而是将其检索为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. JSON结构可实现为对象,记录,结构,字典,哈希表,键列表或关联数组。

You can use eval() function to achieve the desired goal. 您可以使用eval()函数实现所需的目标。 I think this will help you/ 我认为这会帮助您/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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