I am working on updating functional test suites using Cucumber feature file.The issue my output is an array which is not sorted.Index of the object may change.
Array:
[{
"id": "12",
"name": "Something"
},
{
"id": "13",
"name": "Another Something"
}
]
Here I wanna assert name when Id=13 only.Any help would be appreciated.
The Json is list of objects within an Array so you need parse them and validate the each Object. You can do like below,
Code:
JSONArray jsonArray = new JSONArray(JsonAsString);
JSONObject jsonObject;
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject = new JSONObject(jsonArray.get(i).toString());
if (jsonObject.get("id").toString().equalsIgnoreCase("13")) {
System.out.println("Name: " + jsonObject.get("name"));
//do your thing...
}
}
Output:
Name: Another Something
Related
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 :)
I need to get the values of the array "q1" which in array "questions", the arrays is json, and i need the values in java android.
{
"questions": [
{
"q1": [
"what my name?",
"a",
"b",
"c",
"Mac"
],
"q2": [
"what my age?",
"1",
"34",
"80",
"3"
]
}
]
}
Here I am answering your question to solve your problem but My friend you need to study first about json parsing.
Suggestion :
You can find example of it here :
http://primalpappachan.com/android/2010/06/05/parsing-json-in-android/
Answer :
JSONObject jresonseobj = response.getjObj();
JSONObject jobj;
JSONArray jsonArray = new JSONArray(jresonseobj.getString("questions"));
for (int i = 0; i < jsonArray.length(); i++)
{
jobj = jsonArray.getJSONObject(i);
// parse inner json here.
}
I have a JSON string and I am trying to retrieve information from it. Json String looks like this.
JSON STRING :
{
"information": {
"device": {
"id": 0
},
"user": {
"id": 0
},
"data": [
{
"datum": {
"id": "00GF001",
"history_id": "9992BH",
"name": "abc",
"marks": 57,
"class": "B",
"type": "Student"
}
},
{
"datum": {
"id": "72BA9585",
"history_id": "78NAH2",
"name": "ndnmanet",
"marks": 70,
"class": "B",
"type": "Student"
}
},
{
"datum": {
"id": "69AHH85",
"history_id": "NN00E3006",
"name": "kit",
"department": "EF003",
"class": "A",
"type": "Employee"
}
},
{
"datum": {
"id": "09HL543",
"history_id": "34QWFTA",
"name": "jeff",
"department": "BH004",
"class": "A1",
"type": "Employee_HR"
}
}
]
}
}
I am trying to access data JSONArray and respective Datum from it. I differentiated each datum as per type such as student, employee etc and push information in hashmap.
I successfully did it in javascript but in Java I am struggle abit.
When I am trying to access JSONArray it throws exception
try {
JSONObject data = new JSONObject(dataInfo);
// Log.d(TAG, "CHECK"+data.toString());
JSONObject info = data.optJSONObject("information");
if(info.getJSONArray("data").getString(0).equals("Student") > 0) //exception here
Log.d(TAG, "Data"+ data.getJSONArray("data").length()); //exception here too
for(int m = 0; m < data.length(); m++){
// for(int s = 0; s < data[m].ge)
}
} catch (JSONException j){
j.printStackTrace();
}
Any pointers to create hashmap respective type I have. Appreciated
If you're trying to access the type field of a datum object, you'll want something like this:
JSONObject data = new JSONObject(dataInfo); // get the entire JSON into an object
JSONObject info = data.getJSONObject("information"); // get the 'information' object
JSONArray dataArray = info.getJSONArray("data"); // get the 'data' array
for (int i = 0; i < dataArray.length(); i++) {
// foreach element in the 'data' array
JSONObject dataObj = dataArray.getJSONObject(i); // get the object from the array
JSONObject datum = dataObj.getJSONObject("datum"); // get the 'datum' object
String type = datum.getString("type"); // get the 'type' string
if ("Student".equals(type)) {
// do your processing for 'Student' here
}
}
Note that you'll have to deal with exception handling, bad data, etc. This code just shows you the basics of how to get at the data that you're looking for. I separated each individual step into its own line of code so that I could clearly comment what is happening at each step, but you could combine some of the steps into a single line of code if that is easier for you.
if dataInfo is the json you posted, then you have to access information and from information, you can access data:
JSONObject data = new JSONObject(dataInfo);
JSONObject info = data.optJSONObject("information");
if (info != null) {
JSONArray dataArray = info.optJSONArray("data")
}
so, there's this JSON code. Im trying to get the "abridged_cast".
but its complicated.
its JSONObject
inside JSONArray onside jSONObject Inside JsonArray....
{
"total": 591,
"movies": [
{
"title": "Jack and Jill",
"year": 2011,
"runtime": "",
"release_dates": {
"theater": "2011-11-11"
},
"ratings": {
"critics_score": -1,
"audience_score": 90
},
"synopsis": "",
"posters": {
"thumbnail": "",
"profile": "",
"detailed": "",
"original": ""
},
"abridged_cast": [
{
"name": "Al Pacino",
"characters": []
},
{
"name": "Adam Sandler",
"characters": []
},
{
"name": "Katie Holmes",
"characters": []
}
],
"links": {
"self": "",
"alternate": ""
}
}
],
"links": {
"self": "",
"next": ""
},
"link_template": ""
}
this is my code for getting "title" and "year"
if (response != null) {
try {
// convert the String response to a JSON object,
// because JSON is the response format Rotten Tomatoes uses
JSONObject jsonResponse = new JSONObject(response);
// fetch the array of movies in the response
JSONArray movies = jsonResponse.getJSONArray("movies");
// add each movie's title to an array
movieTitles = new String[movies.length()];
for (int i = 0; i < movies.length(); i++) {
JSONObject movie = movies.getJSONObject(i);
movieTitles[i] = movie.getString("title");
}
hope someone would help me because i cant figure out how to get the abridged_cast"
movies contains an array of "movie" objects. Each one of those objects contains a field abridged_cast that is an array of (let's call them "cast member") objects.
If you're not going to map to a POJO and instead are going through the JSON, you simply need to get that array in your loop after getting movie, and get each "cast member" object from that array in the same manner using another loop.
...
JSONArray cast = movie.getJSONArray("abridged_cast");
for (int j = 0; j < cast.length(); j++) {
JSONObject castMember = cast.getJSONObject(j);
...
}
Edit from comments: Your original question involved how to extract the information from the JSON you have; the above code explains that. It now seems like you're asking a more fundamental programming question around how to use it.
If you're going to use the included org.json classes that come with Android, you now know how to access the information in the returned JSON object. And you could write methods around the parsed JSONObject to access the data as-is using the objects and methods from the json.org package. For example, you could write a "getMovie()" method that took the name of the movie as a string and searched that "movies" array for the right one and returned it as a JSONObject.
Normally you would create classes in Java that encapsulate the data returned in that JSON and use data structures that lend themselves to your access patterns (For example, a Map that conatained all the movies using their names as keys). Using the org.json classes you'll have to instantiate those objects and populate them manually as you parse the JSON like you're doing in your question. If you used either the Gson or Jackson JSON parsing libraries they are capable of taking the JSON you have and mapping all the data to the classes your create and returning them in a single call.
try {
String Movie = null;
String abridged = null;
JSONArray jsonResponse = new JSONArray(response);
for (int i = 0; i< jsonResponse.length(); i++) {
Movie = jsonResponse.getJSONObject(i).getString("movies").toString();
System.out.println("movies="+Movie);
abridged = jsonResponse.getJSONObject(i).getString("abridged_cast").toString();
}
JSONArray jArray = new JSONArray(Movie);
for (int i = 0; i< jArray.length(); i++) {
String title = jArray.getJSONObject(i).getString("title").toString();
System.out.println("title="+title);
}
JSONArray jabridgeArray = new JSONArray(abridged);
for (int i = 0; i< jabridgeArray.length(); i++) {
String title = jabridgeArray.getJSONObject(i).getString("name").toString();
System.out.println("title="+title);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I am trying to send the details of Usrs and its items with json. But at time of json genertion, with iterated jsonarry with json object, i stuck t middle.how to manage Jsonrray and JsonObject for below given Iterated data.
{
"Data":
{
["user":1],
"items":
[{"item":1},{"item":2},{"item":3},{"item":4}]
},
{
["user":2],
"items":
[{"item":11},{"item":2},{"item":3},{"item":4}]
},
{
["user":3],
"items":
[{"item":11},{"item":2},{"item":3},{"item":4}]
},
}
I am not sure, whether above given structure is perfect or not?
if perfect then how can I retrieve particular users 4th item?
I feel bad while writing (non-challenging) code for you, but I had my IDE open, and waiting for coffee. So, code for you.
String s = "{\"Data\":[{\"user\":1,\"items\":[{\"item\":1},{\"item\":2},{\"item\":3},{\"item\":4}]},{\"user\":2,\"items\":[{\"item\":11},{\"item\":2},{\"item\":3},{\"item\":4}]},{\"user\":3,\"items\":[{\"item\":11},{\"item\":2},{\"item\":3},{\"item\":4}]}]}";
JSONObject json = new JSONObject(s);
JSONArray data = json.getJSONArray("Data");
for(int i=0; i< data.length(); i++){
JSONObject userData = data.getJSONObject(i);
if(userData.getInt("user") ==2 ){
JSONArray items = userData.getJSONArray("items");
JSONObject item = items.getJSONObject(3);
System.out.println("item#4: " + item.getInt("item"));
}
}
The correct JSON for you is
{
"Data":[
{
"user":1,
"items":
[{"item":1},{"item":2},{"item":3},{"item":4}]
},
{
"user":2,
"items":
[{"item":11},{"item":2},{"item":3},{"item":4}]
},
{
"user":3,
"items":
[{"item":11},{"item":2},{"item":3},{"item":4}]
}
]
}