简体   繁体   English

如何从java中的json文件中获取特定值

[英]how to get specific value from json file in java

I have a json file like this: 我有一个像这样的json文件:

{
    "list": [
        {
            "ID" : "1",
            "value" : "value is one"
        }
        {
            "ID" : "2",
            "value" : "value is two"
        }
        {
            "ID" : "3",
            "value" : "value is three"
        }
        {
            "ID" : "4",
            "value" : "value is four"
        }
    ]
}

what I want to do is read the josn file and returns the message based on the ID i specify. 我想要做的是读取josn文件并根据我指定的ID返回消息。 So for example 所以举个例子

if (this.list.containsKey("1"))
    {
        return this.list.get(messageTitle);
    }

That's what I tried but it returns all the values and ID. 这就是我尝试但它返回所有值和ID。

JSONParser parser = new JSONParser();
try {
    Object obj = parser.parse(new FileReader("jsonFile.json"));
    JSONObject jsonObject = (JSONObject) obj;
    // loop array
    JSONArray msg = (JSONArray) jsonObject.get("list");
    Iterator<String> iterator = msg.iterator();
    while (iterator.hasNext()) {
        System.out.println(iterator.next());
    }
}

How try like this, 如何尝试这样,

 JSONArray msg = (JSONArray) jsonObject.get("list");

 for(int i = 0;i < msg.length();i++ ) {
     JSONObject jsonObj = msg.getJSONObject(i);

     //now get id & value
     int id = jsonObj.getInt("ID");
     String value = jsonObj.getString("value");

     if (1 == id) {
          //now 'value' is what you want
          System.out.println(value);
     }
 }

Note : can break the loop when the result is satisfied. 注意 :当结果满足时可以打破循环。

You can try with TypeReference using ObjectMapper to convert it into appropriate Map object. 您可以使用ObjectMapper尝试使用TypeReference将其转换为适当的Map对象。

sample code: 示例代码:

BufferedReader reader = new BufferedReader(new FileReader(new File("jsonFile.json")));

TypeReference<Map<String, ArrayList<Map<String, String>>>> typeRef = new TypeReference<Map<String, ArrayList<Map<String, String>>>>() {};
ObjectMapper mapper = new ObjectMapper();
try {
    Map<String, ArrayList<Map<String, String>>> data = mapper.readValue(reader, typeRef);
    ArrayList<Map<String, String>> list = data.get("list");
    for (Map<String, String> map : list) {
        if (map.get("ID").equals("1")) {
            System.out.println(map.get("value"));
        }
    }
} catch (Exception e) {
    System.out.println("There might be some issue with the JSON string");
}

output: 输出:

value is one

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

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