簡體   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