简体   繁体   English

无法解析Java JSON字符串

[英]Can't parse Java JSON string

From my server is get a JSON response like this: 从我的服务器获取这样的JSON响应:

String json = getJsonFromServer();

The server returns this reply (with the double quotes in the beginning and end): 服务器返回此答复(在开头和结尾加上双引号):

"{\"error\":\"Not all required fields have been filled out\"}";

I then want to get the error field. 然后,我想获取错误字段。 I have tried to use the JSONObject class to get the string, but it does not work. 我尝试使用JSONObject类获取字符串,但是它不起作用。

System.out.println("The error is: " + new JSONObject().getJSONObject(response).getString("error");

You seem to be using the wrong JSONObject constructor; 您似乎使用了错误的JSONObject构造函数; in your example, you are trying to fetch an object from a newlay created object - it will never exist. 在您的示例中,您尝试从新创建的对象中获取一个对象-它永远不会存在。

Try this: 尝试这个:

String response = "{\"error\":\"Not all required fields have been filled out\"}";

JSONObject json = new JSONObject( response );

String error = json.getString( "error" );

System.out.println( error );

Yields 产量

Not all required fields have been filled out 并非所有必填字段都已填写

edit 编辑

Now that you have completely changed the question... 现在您已经完全改变了问题...

Why not just first strip the first and last char? 为什么不先剥离第一个和最后一个字符?

So if 因此,如果

String response = "\"{\"error\":\"Not all required fields have been filled out\"}\"";

response = response.substring(1, response.length() - 1));

// Now convert to JSONObject

Your response object has exactly this string? 您的响应对象具有此字符串吗?

{"error":"Not all required fields have been filled out"} {“错误”:“未填写所有必填字段”}

The code below printed the expected output: 下面的代码显示了预期的输出:

    Object responseObject = "{\"error\":\"Not all required fields have been filled out\"}";
    JSONObject jsonObject = new JSONObject(responseObject.toString());
    String errorContent = jsonObject.getString("error");
    System.out.println(errorContent);

I have try 我尝试了

String response = "{\"error\":\"Not all required fields have been filled out\"}";
    JSONParser parser = new JSONParser();
    try {
        JSONObject json = (JSONObject) parser.parse(response);

        System.out.println(json.get("error").toString());
    } catch (ParseException ex) {

    }

It have working, you can try it and don't forget add json lib json-simple 它可以正常工作,您可以尝试一下,别忘了添加json lib json-simple

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

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