如何从字符串或json对象中搜索和打印特定内容

时间:2019-07-04 05:48:40

标签: java android json string

我想搜索并打印我从其余API Response存储的jsonobject或字符串的值,并且我想打印"Application with 'Temporarily in New Zealand' status is not allowed"的详细信息的值

    String responseString = EntityUtils.toString(response.getEntity(), "UTF-8");
    JSONObject responseJson = new JSONObject(responseString);
    System.out.println("The response from API is:"+ responseJson);

输出和响应

    {"errors":[{"code":"PredicateValidator","detail":"Application with 'Temporarily in New Zealand' status is not allowed","source":{"source":"/PersonApplicant[0]/ResidencyStatus"},"title":"Application with 'Temporarily in New Zealand' status is not allowed"}]}'

3 个答案:

答案 0 :(得分:0)

您可以通过调用<json-name>.<attribute>来访问JSON对象的属性。似乎您将JSON包装在以JSON包装的列表中,因此请尝试:

your_json_obj.errors[0].detail

那给你

"Application with 'Temporarily in New Zealand' status is not allowed"

答案 1 :(得分:0)

您可以使用JSONObject类从JSON对象访问值。

JSONObject responseJson = new JSONObject(responseString);
JSONArray jsonArray=responseJson.getJSONArray("errors");
for(int i=0; i<jsonArray.lenght();i++){
  JSONObject jso = jsonArray.getJSONObject(i);
  System.out.println(jso.getString("detail"));
}

答案 2 :(得分:0)

您可以使用{Asset}中内置的JSONObject来代替JsonPath

    String responseString = EntityUtils.toString(response.getEntity(), "UTF-8");
    JsonPath path = JsonPath.from(responseString);
    System.out.println("The response from API is: " + path.getString("errors[0].title"));

以上内容将获得错误标题。仅在只有1个错误时可用。