簡體   English   中英

如何從JSON字符串中獲取特定值

[英]how to get a specific value from JSON string

//Open url and fetch JSON data
String s = "MY_URL_HERE";
URL url = new URL(s);
Scanner scan = new Scanner(url.openStream());
String str = new String();
while (scan.hasNext())
{
    str += scan.nextLine();
}
scan.close();

System.out.println(str);

str將輸出類似以下的字符串:

{"coord":{"lon":-80.25,"lat":43.55},"weather":[{"id":800,"main":"Clear","description":"Sky is Clear","icon"...ect

我正在使用json_simple-1.1.jar

我實際上如何使用此字符串提取我選擇的值? 如果我想拉出“說明”或“天氣”。

我嘗試過以下代碼段:

https://code.google.com/p/json-simple/wiki/DecodingExamples

這些對我不起作用,我得到一個錯誤

org.json.simple.JSONObject cannot be cast to org.json.simple.JSONArray

您的字符串不是ant json數組表示形式,而是json對象本身。 那就是org.json.simple.JSONObject cannot be cast to org.json.simple.JSONArray描述的錯誤。 鏈接中的示例描述了一個數組,該數組的每個元素都是一個對象:

考慮一下Jackson libray,它對於將Java對象與JSON相互轉換非常方便。

下面表示一個數組,該數組的每個元素都是一個對象:

[
    {
        color: "red",
        value: "#f00"
    },
    {
        color: "green",
        value: "#0f0"
    }
]

or

[
    {
        "color": "red",
        "value": "#f00"
    },
    {
        "color": "green",
        "value": "#0f0"
    }
]

下面代表對象

{
    color: "red",
    value: "#f00"
}

or

{
    "color": "red",
    "value": "#f00"
}

請參閱此處以獲取json字符串的不同表示形式

使用傑克遜庫的代碼示例

import java.io.IOException;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;


public class TestString {

    public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {

        String s="{\"coord\":{\"lon\":-80.25,\"lat\":43.55},\"weather\":[{\"id\":800,\"main\":\"Clear\",\"description\":\"Sky is Clear\"}]}";
        //String s="[{\"coord\":\"test\",\"lon\":-80.25}]";
        ObjectMapper mapper = new ObjectMapper();
        Object obj = mapper.readValue(s, Object.class );
        System.out.println("terst"+ obj );
    }

}

對於任何將來看這個的人,

使用json_simple-1.1.jar

    String s = "YOUR_URL_HERE";
    URL url = new URL(s);
    Scanner scan = new Scanner(url.openStream());
    String str = new String();
    while (scan.hasNext())
    {
        str += scan.nextLine();
    }
    scan.close();

str現在包含(以我為例)包含更多對象的對象(當我確定這是我想的時候,**將編輯)

現在使用此代碼並使用http://codebeautify.org/jsonviewer

    JSONObject obj = (JSONObject) JSONValue.parse(str);

    String info = obj.get("object_name_you_wish_to_call").toString();

我看到上面的代碼將輸出另一個包含該特定對象內所有信息的對象。在這種情況下,“ object_name_you_wish_to_call”內的所有對象

當我弄清楚如何檢索特定值時,將再次進行編輯。

您可以使用:

  1. 圖案
  2. 匹配
  3. ObjectMapper
  4. JsonNode

Java類:

    private Pattern pattern;
    private Matcher matcher;

    private static final String PATTERN = "description";

    private static String  StringFinal = null;

    public  void printAll(String str) {

        pattern = Pattern.compile(PATTERN);
        String finalPattern = null;  

        ObjectMapper mapper = new ObjectMapper();
        JsonNode node = mapper.readTree(str);
        Iterator<String> fieldNames = node.fieldNames();


        while(fieldNames.hasNext()){
            String fieldName = fieldNames.next();
            JsonNode fieldValue = node.get(fieldName);

            if (fieldValue.isObject()) {
                printAll(fieldValue);
            } 
            else {
                String value = fieldValue.asText();
                matcher = pattern.matcher(value);
                if(matcher.matches()){
                    StringFinal = value;
                    break;
                }
            }
        }

        System.out.println(StringFinal);
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM