[英]How to get the value from this json string in java?
我将以下json字符串作为输出,
{"message":"Error while updating","success":false}
我正在尝试通过使用从中获取json对象,
String resp = "{"message":"Error while updating",
"success":false}";
JSONObject jObject = new JSONObject(resp);
log.info("jObject-success: "+ jObject.getString("success").toString());
在响应错误中找不到上面的行引发“成功”。 我在这里想念什么?
您编写的JSON字符串错误。 使用转义字符。
例如:
String s = "[0,{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}]";
为您的代码
String resp = "{\"message\":\"Error while updating\",\"success\":false}";
让我们创建一个代表您的JSON输入的类
public class Response {
public String message;
public boolean success;
}
并按照以下方式使用Google的gson
库进行解析
Gson gson = new Gson();
Response response = gson.fromJson(resp, Response.class);
System.out.println("Success: " + response.success);
假设您正确定义了resp
并且代码可以编译。
我还假设您正在使用org.json.JSONObject
您将需要使用jObject.getBoolean("success").toString()
。 我记得如果字段不是字符串类型,JSONObject中的getString()
将引发异常。
String resp =字符串输出;
JSONObject对象=新的JSONObject(resp);
System.out.println(object.get(“ message”));
System.out.println(object.get(“ success”)));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.