Hi Below is a simple method which I am using to dynamically generate the JSON request based on Array length from some other API response.
However inside the for loop everything seems to work fine except at the end when JSONArray.add is called, it replaces old jsonObject values inside the array to a new one, and at the end whole array consists of the only same set of JSON objects.
After a lot of debugging can't find the solution, is due to a variable declaration or something. Below is the method I am using
For ref: I am using minidev.JSON
public JSONObject method1(JSONObject sampleJsonObjTemplate, String responseofotherapi) {
JSONArray jsonArray = JsonPath.parse(responseofotherapi).read("$.columns");
JSONArray dataSetColumnArray = new JSONArray();
JSONArray currentJsonColumnArr= JsonPath.parse(dataSetObj).read("$.columns");
JSONObject currentJsonColumnObject= (JSONObject) currentJsonColumnArr.get(0);
LinkedHashMap<String,Object> currentColumn;
for(int columnNumber = 0; columnNumber < jsonArray.size(); columnNumber++){
currentColumn= (LinkedHashMap<String,Object>)jsonArray.get(columnNumber);
String name = currentColumn.get("name").toString();
currentJsonColumnObject.put("name",name);
currentJsonColumnObject.put("alias",name+" Column Alias ");
currentJsonColumnObject.put("description",name+" Column Description ");
dataSetColumnArray.add(columnNumber,currentJsonColumnObject);
currentColumn.clear();
}
JSONObject updatedDataSetReq=JsonPath.parse(dataSetObj).set("$.columns",dataSetColumnArray).json();
return updatedDataSetReq;
}
The problem is with your currentJsonColumnObject object assigning in for loop.
you are using the same object currentJsonColumnObject for all iterations which is referring to currentJsonColumnArr.get(0).
To solve your issue you need to set a different object for currentJsonColumnObject.
JSONArray jsonArray = JsonPath.parse(responseofotherapi).read("$.columns");
JSONArray dataSetColumnArray = new JSONArray();
JSONArray currentJsonColumnArr= JsonPath.parse(dataSetObj).read("$.columns");
//object will be set inside loop
JSONObject currentJsonColumnObject;
LinkedHashMap<String,Object> currentColumn;
for(int columnNumber = 0; columnNumber < jsonArray.size(); columnNumber++){
currentColumn= (LinkedHashMap<String,Object>)jsonArray.get(columnNumber);
// getting object from `currentJsonColumnArr` instead of using the same.
currentJsonColumnObject= (JSONObject) currentJsonColumnArr.get(columnNumber);
String name = currentColumn.get("name").toString();
currentJsonColumnObject.put("name",name);
currentJsonColumnObject.put("alias",name+" Column Alias ");
currentJsonColumnObject.put("description",name+" Column Description ");
dataSetColumnArray.add(columnNumber,currentJsonColumnObject);
currentColumn.clear();
}
I have a JSON object that looks like this
{"layout":[["12","21","31"],["empty","22","32"],["13","23","33"]]}
I am trying to get the array data within with:
JSONObject layoutJson;
JSONArray layoutData = layoutJson.getJSONArray();
However I end up with a single entry in the array of
[["12","21","31"],["empty","22","32"],["13","23","33"]]
How do I get this out of the JSON object in the form of 3 arrays?
JSONObject layoutJson;
JSONArray layoutData = layoutJson.getJSONArray();
for (int i = 0; i < layoutData.length(); i++) {
JSONObject firstArray = (JSONObject)layoutData.getJSONObject(i);
// Do whatever you want with first array
// you can loop through the first array again
}
I have a JAVA for loop which prints the out put as shown below.
inside for loop::{"state":"tess","path":"/content/projectpath/en/men"} inside for loop::{"state":"hello","path":"/content/projectpath/en/women"}
Any my code snippet is as shown below.
for (Value val : values) {
//jsonobj = new JSONObject(val.getString());
out.println("inside for loop::" + val.getString());
// JSONArray jsonarr = val.getString();
}// out.println("::"+jsonobj.toString());
How to get a JSON Array after the for loop which should have the values {"state":"tess","path":"/content/projectpath/en/men"} and {"state":"hello","path":"/content/projectpath/en/women"}
create a JSONArray like this. insert your looping object on list. Finally you will get an array please try it.
JSONArray list = new JSONArray();
list.add(val);
I am building an android app that needs to download and synchronise with an online database, I am sending my query from the app to a php page which returns the relevant rows from a database in JSON format.
can someone please tell me the best way to iterate through a JSON array?
I receive an array of objects:
[{json object},{json object},{json object}]
What is the simplest piece of code I could use to access the JSONObjects in the array?
EDIT: now that I think of it the method I used to iterate the loop was:
for (String row: json){
id = row.getInt("id");
name = row.getString("name");
password = row.getString("password");
}
So I guess I had was somehow able to turn the returned Json into and iterable array. Any Ideas how I could achieve this?
I apologise for my vaguness but I had this working from an example I found on the web and have since been unable to find it.
I think this code is short and clear:
int id;
String name;
JSONArray array = new JSONArray(string_of_json_array);
for (int i = 0; i < array.length(); i++) {
JSONObject row = array.getJSONObject(i);
id = row.getInt("id");
name = row.getString("name");
}
Is that what you were looking for?
I have done it two different ways,
1.) make a Map
HashMap<String, String> applicationSettings = new HashMap<String,String>();
for(int i=0; i<settings.length(); i++){
String value = settings.getJSONObject(i).getString("value");
String name = settings.getJSONObject(i).getString("name");
applicationSettings.put(name, value);
}
2.) make a JSONArray of names
JSONArray names = json.names();
JSONArray values = json.toJSONArray(names);
for(int i=0; i<values.length(); i++){
if (names.getString(i).equals("description")){
setDescription(values.getString(i));
}
else if (names.getString(i).equals("expiryDate")){
String dateString = values.getString(i);
setExpiryDate(stringToDateHelper(dateString));
}
else if (names.getString(i).equals("id")){
setId(values.getLong(i));
}
else if (names.getString(i).equals("offerCode")){
setOfferCode(values.getString(i));
}
else if (names.getString(i).equals("startDate")){
String dateString = values.getString(i);
setStartDate(stringToDateHelper(dateString));
}
else if (names.getString(i).equals("title")){
setTitle(values.getString(i));
}
}
Unfortunately , JSONArray doesn't support foreach statements, like:
for(JSONObject someObj : someJsonArray) {
// do something about someObj
....
....
}
When I tried #vipw's suggestion, I was faced with this exception:
The method getJSONObject(int) is undefined for the type JSONArray
This worked for me instead:
int myJsonArraySize = myJsonArray.size();
for (int i = 0; i < myJsonArraySize; i++) {
JSONObject myJsonObject = (JSONObject) myJsonArray.get(i);
// Do whatever you have to do to myJsonObject...
}
If you're using the JSON.org Java implementation, which is open source, you can just make JSONArray implement the Iterable interface and add the following method to the class:
#Override
public Iterator iterator() {
return this.myArrayList.iterator();
}
This will make all instances of JSONArray iterable, meaning that the for (Object foo : bar) syntax will now work with it (note that foo has to be an Object, because JSONArrays do not have a declared type). All this works because the JSONArray class is backed by a simple ArrayList, which is already iterable. I imagine that other open source implementations would be just as easy to change.
On Arrays, look for:
JSONArray menuitemArray = popupObject.getJSONArray("menuitem");
You are using the same Cast object for every entry.
On each iteration you just changed the same object instead creating a new one.
This code should fix it:
JSONArray jCastArr = jObj.getJSONArray("abridged_cast");
ArrayList<Cast> castList= new ArrayList<Cast>();
for (int i=0; i < jCastArr.length(); i++) {
Cast person = new Cast(); // create a new object here
JSONObject jpersonObj = jCastArr.getJSONObject(i);
person.castId = (String) jpersonObj.getString("id");
person.castFullName = (String) jpersonObj.getString("name");
castList.add(person);
}
details.castList = castList;
While iterating over a JSON array (org.json.JSONArray, built into Android), watch out for null objects; for example, you may get "null" instead of a null string.
A check may look like:
s[i] = array.isNull(i) ? null : array.getString(i);
[I have some code to create a JSON array. In this code I am passing some values to x, y, z in a loop which looks like this.
JSONArray list = new JSONArray();
String jsonText = null;
for (int j = 0; j < 4; j++) {
list.add(new Integer(x));
list.add(new Integer(y));
list.add(new Integer(z));
jsonText = list.toString();
}
System.out.print(jsonText);
This gives output as
[1234,245,10,312,234,122,1234,67788,345,235,001,332]
How can I get these values in a single array like this?
[[1234,245,10],[312,234,122],[1234,67788,345],[235,001,332]] ] I got the answer for this question needs answer for the below question.
I used one of the below solutions.
Thanks for the response from you guys.
Now i got JSON formate nested Arrays which looks like this
[
[[1234,245,10],[312,234,122],[1234,67788,345],[235,001,332]],
[[1234,245,10],[312,234,122],[1234,67788,345],[235,001,332],[1234,67788,3450]],
[[1234,245,10],[312,234,122],[1234,67788,345],[235,001,332],[1234,67788,34534]]]
SO i have One big Array which contains three arrays(this can be 2 or more than three arrays sometimes) and each of these three array contains some arrays, in this above example
what is the reverse procedure ? i mean what if i want those values from these arrays. In the same way how i have did. using JSON
JSONArray list = new JSONArray();
list.get() this get method will give me what i requies ?
I used the org.json Java API.
Thanks friends for helping me till now.
Just put it in another JSONArray.
JSONArray array = new JSONArray();
array.add(list);
String jsonText = array.toString();
Update: as per your comment:
Sorry, the output is something like this
[1234,245,10,312,234,122,1234,67788,345,235,001,332]
Can you please tell how to get the above output like this
[1234,245,10][312,234,122][1234,67788,345][235,001,332]
Several ways:
Concatenate to the jsonString.
String jsonText = ""; // Start with empty string.
for (int j = 0; j < 4; j++) {
JSONArray list = new JSONArray(); // Create new on each iteration.
list.add(new Integer(x));
list.add(new Integer(y));
list.add(new Integer(z));
jsonText += list.toString(); // += concatenates to existing string.
}
System.out.print(jsonText);
Since String concatenating using += in a loop is memory hogging and slow, rather use StringBuilder.
StringBuilder jsonText = new StringBuilder();
for (int j = 0; j < 4; j++) {
JSONArray list = new JSONArray();
list.add(new Integer(x));
list.add(new Integer(y));
list.add(new Integer(z));
jsonText.append(list.toString();
}
System.out.print(jsonText.toString());
I suspect what you want is a syntactically correct JSON array of nested arrays of integers (original post requests invalid JSON). If not, go with #BalusC's answer.
To get an array containing sub-arrays, simply create the sub-arrays as int[] arrays, and add them directly to your main JSONArray.
public int[] getThreeValues() { // example
Random r = new Random();
return new int[] { r.nextInt(100), r.nextInt(100), r.nextInt(100) };
}
public void execute() {
JSONArray master = new JSONArray();
for (int j=0; j<4; j++) {
master.put(getThreeValues());
}
System.out.println(master);
}
Result:
[[3,13,37],[24,4,64],[61,2,1],[97,13,86]]
Note: I'm not sure which JSON library your using, so I used the org.json Java API, which uses put(...) rather than add(...). Also, that particular library supports adding int[] arrays directly to JSONArray - yours may not, in which case you'd need to build the nested JSONArrays and add them to your master.
You can always put the list inside a JSONArray
e.g.
JSONArray list = new JSONArray();
String jsonText = null;
for (int j = 0; j < 4; j++) {
list.add(new Integer(x));
list.add(new Integer(y));
list.add(new Integer(z));
}
JSONArray finalList = new JSONArray();
finalList.put(0, list);
jsonText = finaList.toString();
System.out.print(jsonText);
Or (not recommended at all) hack your output,
e.g.
jsonText += "[" + jsonText + "]";
System.out.print(jsonText);