I am trying to get key and value of json array response. I want to map each key and get its value. Currently I am looping the result of my response.
public void getResult(Object result) {
ObjectMapper mapper = new ObjectMapper();
Object map = null;
try {
map = mapper.readValue((String) result, Object.class);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
JSONArray jsonArray = (JSONArray) map;
for (Object o : jsonArray) {
JSONObject json = new JSONObject((Map) o);
for (Object obj : json.entrySet()) {
Map.Entry entry = (Map.Entry) obj;
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
}
}
Here is the list of objects inside an array
[
{
"uniqueName": "INVinv0001-5179",
"documentType": "Invoice",
"description": "INVinv0001-5179",
"assignedDate": "2020-10-22",
"approver": "10011618",
"email": "adrian.cabral#example.com",
"fullURL": "http://localhost:8080/webjumper?itemID=AEz0AQNDZtZ%21ca3&awcharset=UTF-8",
"attachments": [
"AEz0ACMDZtZ!cnN"
]
},
{
"uniqueName": "INVinv0001-5179",
"documentType": "Invoice",
"description": "INVinv0001-5179",
"assignedDate": "2020-10-22",
"approver": "10003025",
"email": "dummy#example.com",
"fullURL": "http://localhost:8080/webjumper?itemID=AEz0AQNDZtZ%21ca3&awcharset=UTF-8",
"attachments": [
"AEz0ACMDZtZ!cnN"
]
}
]
I keep getting this error.
java.lang.ClassCastException: class java.util.ArrayList cannot be cast to class org.json.simple.JSONObject
Try to convert map object to JSONArray rather than JSON Object. It would give you JSONObject to work with directly.
public void getResult(Object result) {
ObjectMapper mapper = new ObjectMapper();
Object map = null;
try {
map = mapper.readValue((String) result, Object.class);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
JSONArray json = (JSONArray) map;
for (int i=0; i < json.length(); i++) {
JSONObject e = json.get(i);
System.out.println(e);
}
}
You are casting it wrong.
JSONObject json = (JSONObject) map;
This casting is wrong (JSONObject) map. it should be (JSONArray) map.
Next time before casing object, you perhaps want to check type of object like this.
System.out.println(map.getClass().getName());
Related
I've a JSON file with:
"items": [
{
(...)
"volumeInfo": {
(...)
"readingModes": {
"text": true,
"image": true
},
(...)
}
How do I access 'image' and 'text' in "readingModes"? I've tried both
JSONArray readingModes = volumeInfo.optJSONArray("readingModes");
which worked for data with squared bracket, but in this case returns nulls
and
JSONObject readingModes = gobj.getJSONObject("readingModes");
which returns error - JSONObject["readingModes"] not found, where gobj is accessed:
JSONObject jobj = new JSONObject(jsonData);
JSONArray items = jobj.getJSONArray("items");
Iterator i = items.iterator();
while(i.hasNext())
{
JSONObject gobj = (JSONObject) i.next();
(...)
}
JSONObject jobj = new JSONObject(jsonData);
JSONArray items = jobj.getJSONArray("items");
Iterator i = items.iterator();
while(i.hasNext())
{
JSONObject gobj = (JSONObject) i.next();
JSONObject volumeInfo = gobj.getJSONObject('volumeInfo');
JSONObject readingModes = volumeInfo.getJSONObject('readingModes');
(...)
}
According to your JSON you need to do this.
Since readingModes is in volumeInfo, you first need to get JSON object of volumeInfo in order to access readingModes.
{
"type":
"coll",
"locations":[
{"geometry":
{"Coords":
[54.7,46.7]
}
},
{"geometry":
{"Coords":
[54.7,46.7]
}
},
{"geometry":
{"Coords":
[54.7,46.6]
}
},
{"geometry":
{"Coords":
[54.64999833333333,46.6]
}
}
]
}
In java using json.simple,here the code:
Here i assume the json data is present in file.json
Object obj = parser.parse(new FileReader( "file.json" ));
JSONObject jsonObject = (JSONObject) obj;
JSONArray loc= (JSONArray) jsonObject.get("locations");
Iterator i = loc.iterator();
while (i.hasNext()) {
JSONObject geo = (JSONObject) (i.next());
JSONObject coords = (JSONObject)geo.get("geometry");
String coord= (String)coords.get("Coords");
System.out.println(coord);
}
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>>)
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();
}
}
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){
}
I have a json file like this
[ {
"id":"serve-coffee",
"tags":[ {
"name": "#tag1", "line": 1
}
],
"description":"Coffee should not be served\n",
"name":"Serve coffee",
"keyword":"Feature",
"line":2,
"elements":[ {
"id": "serve-coffee;buy-last-coffee", "tags":[ {
"name": "#tag2", "line": 6
}
],
"description":"",
"name":"Buy last coffee",
"keyword":"Scenario",
"line":7,
"steps":[ {
"name": "there are 1 coffees left in the machine", "keyword": "Given ", "line": 8
}
,
{
"name": "I have deposited 1$", "keyword": "And ", "line": 9
}
],
"type":"scenario"
}
],
"uri":"src\/test\/resources\/traffic-remove-locations.feature"
}
]
Iam trying to convert the above json file to JSONObject.But am getting class cast exception "java.lang.ClassCastException: org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject"
code
public static JSONObject convertFileToJSON(String fileName) throws ParseException {
// Read from File to String
JSONParser parser = new JSONParser();
JSONObject jsonObject = null;
try {
Object object = parser.parse(new FileReader(fileName));
jsonObject = (JSONObject) object; // Getting classCast Exception here.
} catch (FileNotFoundException e) {
} catch (IOException ioe) {
}
return jsonObject;
}
but when i changed the line jsonObject = (JSONObject) object; to JSONArray jsonArray = (JSONObject)object the exception disappears.
But if am casting to JSONArray then how can i get the values like id,tags and description from JSONArray.
please provide a suggestion guys
Your JSON file represents an array with one object in it. So if that were a Java data structure, you're effectively doing this:
int[] arr = {5};
int i = (int)arr;
This obviously doesn't work because you can't cast an array to a singular object. What you actually want to do it pull out the first element of the array. To continue the Java example, you want to do
int[] arr = {5};
int i = (int)arr[0];
With the JSON stuff, your parser.parse() call returns a JSONArray, not a JSONObject. So you'll need to do something like this:
public static JSONObject convertFileToJSON(String fileName) throws ParseException {
JSONParser parser = new JSONParser();
JSONObject jsonObject = null;
try {
JSONArray array = (JSONArray) parser.parse(new FileReader(fileName));
jsonObject = array.getJsonObject(0);
} catch (FileNotFoundException e) {
} catch (IOException ioe) {
}
return jsonObject;
}
Try casting to JsonArray and then cast access the objects one by one with help of the index from the JSON array.
Object object = parser.parse(new FileReader(fileName));
JsonArray jsonArr = (JsonArray) object; // Getting c
jsonObject jsonObj = jsonArr.get(0); //use index to access like a list
I was also facing the same issue. I did the below changes to make it work.
Below is my sample JSON.
{
"routes": [{
"startTime": 1520319414,
"routeInfo": [{
"routePart": 0,
"transType": "WALK",
"transDetails": {
"startLoc": {
"lat": 28.6434862,
"lon": 77.22542659999999
}
}
}, {
"routePart": 1,
"transType": "BUS",
"transDetails": {
"routeNumber": "307-U",
"interStopDetails": [{
"seq": 1,
"name": "test1",
"loc": {
"lat": 28.64302,
"lon": 77.2260367
},
"eta": 1520319600
}
]
}
}
],
"totalTime": 5742
}
]
}
Solution to Parse:
JSONObject obj = (JSONObject) jsonParser.parse(new FileReader(FilepathDummy));
JSONArray jsonRoutes= (JSONArray) obj.get("routes"); //Gives Main JSoN
JSONObject routeJsonObject = (JSONObject) jsonRoutes.get(0); // Route Array into JSON
JSONArray routeInfoArray = (JSONArray) routeJsonObject.get("routeInfo"); // RouteInfo Array
Hope this solve your problem.
I am facing issue in looping in the following code,i am passing a list of forms to it,i am not sure what is going wrong,i need the output as but i am getting only the last form_id.I have this code to get this output as ,here i am passing a list of forms and getting the json as output. Please let me know where am i going wrong.
output :
{
"forms": [
{ "form_id": "1", "form_name": "test1" },
{ "form_id": "2", "form_name": "test2" }
]
}
code :
public class MyFormToJSONConverter {
public JSONObject getJsonFromMyFormObject(List<Form> form) {
JSONObject responseDetailsJson = new JSONObject();
JSONArray jsonArray = null;
List<JSONArray> list = new ArrayList<JSONArray>();
System.out.println(form.size());
for (int i = 0; i < form.size(); i++) {
JSONObject formDetailsJson = new JSONObject();
formDetailsJson.put("form_id", form.get(i).getId());
formDetailsJson.put("form_name", form.get(i).getName());
formDetailsJson.put("desc",
form.get(i).getFormDescription());
jsonArray = new JSONArray();
jsonArray.add(formDetailsJson);
list.add(jsonArray);
}
for (JSONArray json : list) {
responseDetailsJson.put("form", json);
}
return responseDetailsJson;
}
Your problem is here:
for (JSONArray json : list) {
responseDetailsJson.put("form", json);
}
will overwrite all of the previous values with the next value (a single JSON object). You want
responseDetailsJson.put("form", list);
You probably should also get rid of this:
jsonArray = new JSONArray();
jsonArray.add(formDetailsJson);
list.add(jsonArray);
That will give you:
{
"forms": [
[{ "form_id": "1", "form_name": "test1" }],
[{ "form_id": "2", "form_name": "test2" }]
]
}
All told, I think you want:
JSONObject responseDetailsJson = new JSONObject();
List<JSONObject> list = new ArrayList<JSONObject>();
System.out.println(form.size());
// List.get will be very inefficient if passed a LinkedList
// instead of an ArrayList.
for (Form formInstance:form) {
JSONObject formDetailsJson = new JSONObject();
formDetailsJson.put("form_id", formInstance.getId());
formDetailsJson.put("form_name", formInstance.getName());
formDetailsJson.put("desc",
formInstance.getFormDescription());
list.add(formDetailsJson);
}
responseDetailsJson.put("form", list);
JSON objects are essentially key/value pairs. In your code you are doing:
for (JSONArray json : list)
{
responseDetailsJson.put("form", json);
}
You're overwriting the same key each time.