简体   繁体   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 will print a string like : str将输出类似以下的字符串:

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

I am using json_simple-1.1.jar 我正在使用json_simple-1.1.jar

How do I actually use this string to extract values of my choosing? 我实际上如何使用此字符串提取我选择的值? If i wanted to pull out the "description" or the "weather". 如果我想拉出“说明”或“天气”。

I have tried snippets from: 我尝试过以下代码段:

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

These do not work for me, I get an error 这些对我不起作用,我得到一个错误

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

Your string is not ant json array representation but json object itself . 您的字符串不是ant json数组表示形式,而是json对象本身。 Thats what error org.json.simple.JSONObject cannot be cast to org.json.simple.JSONArray depicts. 那就是org.json.simple.JSONObject cannot be cast to org.json.simple.JSONArray描述的错误。 Example in your link describes an array, and each element of that array is an object: 链接中的示例描述了一个数组,该数组的每个元素都是一个对象:

Consider Jackson libray which is very convenient for converting Java object to / from JSON 考虑一下Jackson libray,它对于将Java对象与JSON相互转换非常方便。

Below represent an array, and each element of that array is an object: 下面表示一个数组,该数组的每个元素都是一个对象:

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

or

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

Below represent the object 下面代表对象

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

or

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

See here for different representation of json string 请参阅此处以获取json字符串的不同表示形式

Code sample using jackson library 使用杰克逊库的代码示例

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 );
    }

}

for anyone looking at this in the future, 对于任何将来看这个的人,

using json_simple-1.1.jar 使用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 now contains (in my case) an object containing more objects (**will edit when when I am sure, this is what I think) str现在包含(以我为例)包含更多对象的对象(当我确定这是我想的时候,**将编辑)

now using this code and using http://codebeautify.org/jsonviewer 现在使用此代码并使用http://codebeautify.org/jsonviewer

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

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

I see that the code above will output another Object containing all informaiton within that specific object.. In this case, all of the objects within "object_name_you_wish_to_call" 我看到上面的代码将输出另一个包含该特定对象内所有信息的对象。在这种情况下,“ object_name_you_wish_to_call”内的所有对象

when I figure out how to retrieve a specific value, I will edit again. 当我弄清楚如何检索特定值时,将再次进行编辑。

You can do this using : 您可以使用:

  1. Pattern 图案
  2. Matcher 匹配
  3. ObjectMapper ObjectMapper
  4. JsonNode JsonNode

Java class : 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