Java 从API返回解析正则表达式
我想寻求有关如何解析此字符串的帮助Java 从API返回解析正则表达式,java,android,regex,string,string-parsing,Java,Android,Regex,String,String Parsing,我想寻求有关如何解析此字符串的帮助 {"success":false,"error":{"code":500,"message":"No keyword found."}} 我希望能够获得错误代码和错误消息。我唯一的问题是找到一个正则表达式,它可以捕获我一直停留在的值 Pattern pattern = Pattern.compile(REGEX?); Matcher matcher = pattern.matcher(result); 在Java中,我们通常不会为这些琐碎的任务编译模式 快
{"success":false,"error":{"code":500,"message":"No keyword found."}}
我希望能够获得错误代码和错误消息。我唯一的问题是找到一个正则表达式,它可以捕获我一直停留在的值
Pattern pattern = Pattern.compile(REGEX?);
Matcher matcher = pattern.matcher(result);
在Java中,我们通常不会为这些琐碎的任务编译模式 快速回答
如果结果有逗号,这将不起作用。您需要将其解析为json并获取值而不是正则表达式,因为您的响应是json
JSONObject message = new JSONObject(yourResponse);
// use myJson as needed, for example
JSONObject error = message.getJSONObject(“error”);
int code = error.getInt(“code”);
String message2 = error.getString(“message”);
如果你想要正则表达式,就是这个
s = s.replaceAll(".*\"code\":(.+?),.*", "$1");
这个图书馆很容易使用。示例代码如下所示:
JSONObject obj = new JSONObject(" .... ");
int errCode= obj.getJSONObject("error").getInt("code");
这个字符串是json格式的,最好使用json解析器。试试这个:
String s = "{\"success\":false,\"error\":{\"code\":500,\"message\":\"No keyword found.\"}}";
JSONObject jsonObject;
try {
jsonObject = new JSONObject(s);
JSONObject error = (JSONObject) jsonObject.get("error");
System.out.println(error.get("message"));
System.out.println(error.get("code"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
另外,请看一看。它看起来非常像JSON。你可以这样解析它吗?为什么不使用json解析器?这看起来像json字符串,你应该解析itHmm,将Strign转换为int?你可以看到,代码返回为int,其格式为json格式。这是我的错误。对不起,是你的评论错了。为什么程序员如此防御性?嗨,我试过了,但它给了我05-22 14:28:19.847:W/System.err13787:org.json.JSONException:java.lang.String类型的内部值不能转换为JSONObject message=new JSONObjectstatus.message行上的JSONObject;
String s = "{\"success\":false,\"error\":{\"code\":500,\"message\":\"No keyword found.\"}}";
JSONObject jsonObject;
try {
jsonObject = new JSONObject(s);
JSONObject error = (JSONObject) jsonObject.get("error");
System.out.println(error.get("message"));
System.out.println(error.get("code"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}