I have JSON object as follows:
member = "{interests : [{interestKey:Dogs}, {interestKey:Cats}]}";
In Java I want to parse the above json object and store the values in an arraylist.
I am seeking some code through which I can achieve this.
We can have duplicate keys in a JSON object, and it would still be valid. The validity of duplicate keys in JSON is an exception and not a rule, so this becomes a problem when it comes to actual implementations.
The short answer: Yes but is not recommended.
You will need to convert the JSON to Java Objects and then perform the duplicate removal operation. Added code snippet for each of the steps. Hope this helps! You will need to convert the JSON to Java Objects and then perform the duplicate removal operation.
Thanks. The JSON RFC says "the names within an object SHOULD be unique" so implementations will differ. You may find one that has more relaxed rules.
I'm assuming you want to store the interestKeys in a list.
Using the org.json library:
JSONObject obj = new JSONObject("{interests : [{interestKey:Dogs}, {interestKey:Cats}]}"); List<String> list = new ArrayList<String>(); JSONArray array = obj.getJSONArray("interests"); for(int i = 0 ; i < array.length() ; i++){ list.add(array.getJSONObject(i).getString("interestKey")); }
public class JsonParsing { public static Properties properties = null; public static JSONObject jsonObject = null; static { properties = new Properties(); } public static void main(String[] args) { try { JSONParser jsonParser = new JSONParser(); File file = new File("src/main/java/read.json"); Object object = jsonParser.parse(new FileReader(file)); jsonObject = (JSONObject) object; parseJson(jsonObject); } catch (Exception ex) { ex.printStackTrace(); } } public static void getArray(Object object2) throws ParseException { JSONArray jsonArr = (JSONArray) object2; for (int k = 0; k < jsonArr.size(); k++) { if (jsonArr.get(k) instanceof JSONObject) { parseJson((JSONObject) jsonArr.get(k)); } else { System.out.println(jsonArr.get(k)); } } } public static void parseJson(JSONObject jsonObject) throws ParseException { Set<Object> set = jsonObject.keySet(); Iterator<Object> iterator = set.iterator(); while (iterator.hasNext()) { Object obj = iterator.next(); if (jsonObject.get(obj) instanceof JSONArray) { System.out.println(obj.toString()); getArray(jsonObject.get(obj)); } else { if (jsonObject.get(obj) instanceof JSONObject) { parseJson((JSONObject) jsonObject.get(obj)); } else { System.out.println(obj.toString() + "\t" + jsonObject.get(obj)); } } } }}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With