-4

I have key value pairs of <string, string> where value is json array.

I need to get parse this json to get output depending on value of name which is wanted in this case.

Input

"123" : [{ name : "wanted", value : "v1"   }, {name : "wanted", value : "v2" }, {name : "unwanted", value : "v3" }]

Output

{"123": ["v1","v2"]} 

(like Map<String,List<String>>)

user1298426
  • 3,467
  • 15
  • 50
  • 96
  • At first you can see here: http://stackoverflow.com/questions/2591098/how-to-parse-json-in-java?rq=1 – Vasyl Lyashkevych Apr 26 '17 at 16:54
  • Sorry but your question is quite unclear. Are you trying to filter from your array entries with ` name : "unwanted"` and get only `value` from `wanted`? If yes then output should probably be `123 [v2, v3]`. – Pshemo Apr 26 '17 at 16:54
  • Have you tried anything? – tnw Apr 26 '17 at 16:57

2 Answers2

0

You need to parse object "123" and later list of objects { name : "..", value : ".." }

JSONParser parser = new JSONParser();

    try {

        Object obj = parser.parse(new FileReader("*.json"));

        JSONObject jsonObject = (JSONObject) obj;

        String name = (String) jsonObject.get("name");

        long value = (Long) jsonObject.get("value");

        // loop array
        JSONArray msg = (JSONArray) jsonObject.get(" name of 123 ");
        Iterator<String> iterator = msg.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    }

    }
Vasyl Lyashkevych
  • 1,920
  • 2
  • 23
  • 38
0

Hey you can use Json Simple library for doing this. Download jar from https://code.google.com/archive/p/json-simple/downloads. Here is the code snippet for your specific case that how will you parse your object where only wanted name value should be added in the list:

try{
    JSONParser parser = new JSONParser();
    JSONObject jsonObject = (JSONObject) parser.parse("{\"123\" : [{\"name\" : \"wanted\", \"value\" : \"v1\"   }, {\"name\" : \"wanted\", \"value\" : \"v2\" }, {\"name\" : \"unwanted\", \"value\" : \"v3\" }]}");
    JSONArray jsonArray = (JSONArray) jsonObject.get("123");
    List<String> valueList = new ArrayList<>();
    for(int i=0;i<jsonArray.size();i++){
        JSONObject o = (JSONObject) jsonArray.get(i);
        if(o!=null && "wanted".equals(o.get("name"))){
            String value = (String) o.get("value");
            valueList.add(value);
        }
    }
    Map<String,List<String>> map = new HashMap<>();
    map.put("123",valueList);
    System.out.println(map);
}catch(Exception e){

}
Samarth
  • 773
  • 1
  • 6
  • 14