Need to iterate the json array object using java please some guid me on this
I have posed my JSON structure Below are the json given by developer i need to get the json array object as a input for my selenium script.
Can some one please help me on this?
[{
"Name": "Name1",
"Address": "Address",
"PhoneNo": 2142751,
"Courses": [{
"CourseName": "JAVA",
"Cost": 12000
},
{
"CourseName": "Testing",
"Cost": 12000
}
]
},
{
"Name": "Name2",
"Address": "Address2",
"PhoneNo": 214275143,
"Courses": [{
"CourseName": "JAVAV2",
"Cost": 12000
},
{
"CourseName": "Security",
"Cost": 12000
}
]
}
]
Expected String name = value of Name String courseName = value of CourseName
Well, here we just import the class ObjectMapper, than of course, whe have to instantiate it in the class we need. After that, call the function:
Object object = objectMapper.readValue(jsonAsString, Object.class);
Maybe that works for you.
You have many options to read a JSON, you can use JSONArray from primefaces library or JsonArray from google library.
In this case im using import org.primefaces.json.JSONArray;
Be sure to have that library or jar, or dependency if using maven.
To get name and courseName do as follow:
JSONArray jArray = new JSONArray(yourJsonStringGoesHere);
String name = jArray.getJSONObject(0).getString("Name");
String courseName = jArray.getJSONObject(0).getJSONArray("Courses").getJSONObject(0).getString("CourseName");
Also, if you need to get every single name and courseName from the JSON you can do a for loop like this:
// JSONArray made with your JSON String
JSONArray jArray = new JSONArray(yourJsonString);
// JSONArray made with the sub array of courses in your JSON
JSONArray jArrayCourses = jArray.getJSONObject(0).getJSONArray("Courses");
// Loop trough your JSON array
for (int i = 0; i < jArray.length(); i++) {
// Get name of each JSONObject inside your array
String name = jArray.getJSONObject(i).getString("Name");
System.out.println("name: "+name);
// Loop trough each sub array of courses.
for (int j = 0; j < jArrayCourses.length(); j++) {
// Get courseName of each JSONObject inside your courses sub array
String courseName = jArray.getJSONObject(i).getJSONArray("Courses").getJSONObject(j)
.getString("CourseName");
System.out.println("courseName: "+courseName);
}
}
Output
name: Name1
courseName: JAVA
courseName: Testing
name: Name2
courseName: JAVAV2
courseName: Security
Ask me if you don't understand something or need more help im feeling generous today :)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.