Reputation: 91
I am having a JSON file that consists of JSON Objects and arrays. The file looks like this:
{"Report": {"Information": [
{
"table_name1": [
{"ID": 312},
{"LASTNAME": "TESTER2"},
{"GUID": "ADSA31321"},
{"PHONE_MOBILE": 931024}}
],
"table_name2": [
{"ID": 312},
{"PID": "TESTER2"},
{"GUID": "ADSA31321"}
]
}
]}}
I am trying to update the values within the table_name array. The problem is that this name is dynamic and not a static name given to the array.
I am using the Java class below to reach ID.
if( inputJs.getJSONObject("Report").get("Information") instanceof JSONArray) {
JSONArray val= inputJs.getJSONObject("Report").getJSONArray("Information");
for(int i = 0; i < val.length(); i++) {
JSONArray jsa2=val.getJSONArray(i);
for(int j = 0; j < jsa2.length(); j++) {
JSONObject jso= jsa2.getJSONObject(j);
if(jso.equals("GUID")) {
jso.put("GUID", GetRegExpr(3));
}
}
}
}
This line : JSONArray jsa2=val.getJSONArray(i);
creates the error below:
org.json.JSONException: JSONArray[0] is not a JSONArray.
even though "table_name1" is a JSONArray.
Any help will be appreciated.
Upvotes: 0
Views: 1082
Reputation: 854
Please replace your code with the one below
if( inputJs.getJSONObject("Report").get("Information") instanceof JSONArray){
JSONArray infoArray = inputJs.getJSONObject("Report").get("Information");
for (int i = 0; i < infoArray.length(); i++) {
JSONObject information = infoArray.getJSONObject(i);
Iterator<String> keys = information.keys();
while (keys.hasNext()) {
String tableName = keys.next();
JSONArray table = information.getJSONArray(tableName);
for (int j = 0; j < table.length(); j++) {
JSONObject data = table.getJSONObject(j);
String k = data.keys().next();
if (k.equals("GUID")) {
data.put("GUID", GetRegExpr(3));
}
}
}
}
}
Upvotes: 1
Reputation: 69
Try this...
informationList = new JSONObject().getJSONObject("Report").getJSONArray("Information");
for (int i = 0; i < informationList.length(); i++) {
JSONObject information = informationList.getJSONObject(i);
Iterator<String> keys = information.keys();
while (keys.hasNext()) {
String tableName = keys.next();
JSONArray table = information.getJSONArray(tableName);
for (int j = 0; j < table.length(); j++) {
JSONObject data = table.getJSONObject(j);
String k = data.keys().next();
if (k.equals("GUID")) {
data.put("GUID", "edit ...");
}
}
}
}
If I were you, I would use other library like Gson...
Upvotes: 2
Reputation: 396
you can try like this :
if( inputJs.getJSONObject("Report").get("Information") instanceof JSONArray){
JSONArray val= inputJs.getJSONObject("Report").getJSONArray("Information");
for(int i=0;i<val.length();i++){
JSONObject jsa2=val.getJSONObject("table_name"+i); // table_name1,table_name2,...
for(int j=0;j<jsa2.length();j++){
JSONObject jso= jsa2.getJSONObject(j);
if(jso.equals("GUID")){
jso.put("GUID",GetRegExpr(3));
}
}
}
Upvotes: 1