I have a json array : [{"choice":"Yes","score":"1"},{"choice":"No","score":"0"},{"choice":"Not Done","score":"0"}]
How can I get the key and the value of the json? I want to store into database the choice and the score value.
-
3Did you tried anything? There are lot of JSON libraries that you can use to handle JSONThusitha Thilina Dayaratne– Thusitha Thilina Dayaratne2014-10-20 10:22:26 +00:00Commented Oct 20, 2014 at 10:22
-
@Miss_Ann get help from hereAnkur Singhal– Ankur Singhal2014-10-20 10:24:15 +00:00Commented Oct 20, 2014 at 10:24
-
2Please post code that you may have tried. In order to handle JSON in java, as Thusitha Thilina Dayaratne pointed out there a lot of JSON libraries; Most of these libraries depend on you creating a POJO class. You may want to look at GSON library.Parth– Parth2014-10-20 10:25:11 +00:00Commented Oct 20, 2014 at 10:25
-
possible duplicate of How separate keys and values in this JSON object, using Java?OshoParth– OshoParth2014-10-20 10:29:10 +00:00Commented Oct 20, 2014 at 10:29
-
1You can Refer To this for help :stackoverflow.com/questions/14825632/…OshoParth– OshoParth2014-10-20 10:30:07 +00:00Commented Oct 20, 2014 at 10:30
Add a comment
|
2 Answers
thanks for the response guys. i have use Jackson library to convert JSON to map, then it solves my problem.
Map<String,String> map = new HashMap<String,String>();
ObjectMapper mapper = new ObjectMapper();
//convert JSON string to Map
map = mapper.readValue((String)jsonarray.get(word0), new TypeReference<HashMap<String,String>>(){});
System.out.println(map);
System.out.println(map.get("choice"));
System.out.println(map.get("score"));
Comments
This is an another solution to get data from jsonArray using JSONParser
FileReader reader = new FileReader(filePath);// the file which has json data
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
// get an array from the JSON object
JSONArray lang= (JSONArray) jsonObject.get("key");
// take the elements of the json array
for(int i=0; i<lang.size(); i++){
System.out.println("The " + i + " element of the array: "+lang.get(i));
}
Iterator i = lang.iterator();
// take each value from the json array separately
while (i.hasNext()) {
JSONObject innerObj = (JSONObject) i.next();
System.out.println(innerObj.get("key1") +
+ innerObj.get("key2"));
}