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

时间:2014-08-22 11:50:15

标签: java json

我有一个像这样的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"
        }
    ]
}

我想要做的是读取josn文件并根据我指定的ID返回消息。例如,

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

这就是我尝试过但它会返回所有值和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());
    }
}

2 个答案:

答案 0 :(得分:3)

如何尝试这样,

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

注意:在满足结果时打破循环。

答案 1 :(得分:0)

您可以尝试使用TypeReference ObjectMapper将其转换为相应的地图对象。

示例代码:

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

输出:

value is one