繁体   English   中英

如何从 Java 中的 Json 获取特定字段?

[英]How do i get particular field from the Json in Java?

假设,我有一个 Json,我想从 Json 中获取特定字段的值,那么我该如何实现呢?

请打开以下链接查看 json。

json: https ://jsoneditoronline.org/ ? id = 05f3f2de21184ea19a105b4e5219c675

现在,我想获取我们可以在 object->changelog->history->0->created/1->created/2->created....30->created 中找到的所有“创建”的值。

如果需要,我们也可以参考左侧的 json。

如何在java代码中获取created的值? 请在这里帮助我。

您可以使用 org.json,并使用 JSONObject 您可以获得您想要的

JSONObject json = new JSONObject(yourjsonString);

---在评论后添加---

我建议你:

JSONObject json = new JSONObject(yourjsonString);//it's object
JSONObject changelog = json.getJSONObject("changelog");
JSONArray histories = changelog.getJSONArray("histories");
histories.getJSONObject(0); //first json in histories

如果你愿意,你可以连接。
亲自尝试以得到您想要的东西。

调用您的 url 以检索您的 json 内容。

String jsonString = requestInfoFromUrl(urlLink);   

private String requestInfoFromUrl(String url) throws IOException {
      UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url);
      HttpGet getMethod = new HttpGet(builder.build().toUri());
      HttpResponse response = httpClient.execute(getMethod);

      if (response.getStatusLine().getStatusCode() == 200){
             return EntityUtils.toString(response.getEntity());
      } else {
             LOG.error("Error appear while request response from an url.");
             return null;
      }
}

现在,在 jsonString 中,我们拥有来自 url 的所有 json。 现在让我们从该 json 中检索一个字段(changelog 字段):

String changelog = extractFromJsonAStringWithKey(jsonString, "changelog");

 private String extractFromJsonAStringWithKey(String jsonString, String key){
        JSONObject jsonObject = new JSONObject(jsonString);
        return (String) jsonObject.get(key);
}

最好的方法是使用一些专门用于它的库,例如:

暂无
暂无

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

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