Android JSON Parse Getting Array within Array - java

Seems like a simple problem, and I know there are multiple questions like this already. I'm trying to get JSON data from an Array within an Array.
I have a JSON Array as follows:
{
"results": [
{
"name": "John Doe",
"time": "09:00:00",
"claim": {
"date": "2015-08-06",
"comments": "Some comments"
}
},
{
"name": "Mary Smith",
"time": "10:00:00",
"claim": {
"date": "2015-08-06",
"comments": "Some comments"
}
}
}
]
}
I'm trying to parse all the information out of it, I'm able to get the name and time but i'm having trouble getting the data out of the claim array.
I have view multiple similar problems here on SO but none of their solutions fixed my problem.
Here is my Java Code:
#Override
protected void onPostExecute(JSONObject json) {
if (dialog.isShowing()) {
dialog.dismiss();
}
try {
// Getting JSON Array from URL
JSONArray android = json.getJSONArray(TAG_RESULTS);
for (int i = 0; i < android.length(); i++) {
JSONObject c = android.getJSONObject(i);
// Storing JSON items in Variables
String time = c.getString(TAG_TIME);
//For loop for claims array:
JSONArray claims = c.getJSONArray(TAG_CLAIM);
for (int j = 0; j < claims.length(); j++) {
JSONObject d = claims.getJSONObject(j);
String name = d.getString(TAG_NAME);
//other parsing and list view.
I'm getting this error:
org.json.JSONException: Value {"date": "2015-08-06","comments": "Some comments"} at claim of type org.json.JSONObject cannot be converted to JSONArray
08-06 12:43:27.436 17586-17586/com.murrion.navigationdrawer W/System.err﹕ at org.json.JSON.typeMismatch(JSON.java:100)
08-06 12:43:27.436 17586-17586/com.murrion.navigationdrawer W/System.err﹕ at org.json.JSONObject.getJSONArray(JSONObject.java:588)
On this line: JSONArray claims = c.getJSONArray(TAG_CLAIM);
I'm not sure what is going wrong, I'd greatly appreciate some help. Thanks

claim is not an array, but another object. If you want it to be an array, it should be something like this:
"claim": [
"date": "2015-08-06",
"comments": "Some comments"
]
(notice the [ ] instead of { })
If it's meant to be an object, then the code should read:
JSONObject claims = c.getJSONObject(TAG_CLAIM);

Try this
{
"results": [
{
"name": "John Doe",
"time": "09:00:00",
"claim": [
"date": "2015-08-06",
"comments": "Some comments"
]
},
{
"name": "Mary Smith",
"time": "10:00:00",
"claim": [
"date": "2015-08-06",
"comments": "Some comments"
]
}
]
}
Note: The problem in your json is clearly mentioned in the Error stack trace, which tells you that you are trying to parse the json object(within {...}) as json array(array should be within[...], not {...}). So please try to read the stack trace.

After removing the Extra } curly braces you json will be like this
{
"results" :
[
{
"name" : "John Doe",
"time" : "09:00:00",
"claim" :
{
"date" : "2015-08-06",
"comments" : "Some comments"
}
},
{
"name" : "Mary Smith",
"time" : "10:00:00",
"claim" :
{
"date" : "2015-08-06",
"comments" : "Some comments"
}
}
]
}
and to parse this json your code like this
#Override
protected void onPostExecute(JSONObject json)
{
if (dialog.isShowing()) {
dialog.dismiss();
}
try
{
// Getting JSON Array from URL
JSONArray android = json.getJSONArray(TAG_RESULTS);
for (int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
// Storing JSON items in Variables
String time = c.getString(TAG_TIME);
String time = c.getString("name");
// for claims object:
JSONObject claims = c.getJSONObject(TAG_CLAIM);
String date= claims .getString("date");
String comments= claims .getString("comments");
//other parsing and list view.
}
}
catch(Exception e){}
}
as you are saying your json should be like this
{
"results" :
[{
"name" : "John Doe",
"time" : "09:00:00",
"claim" : [{
"date" : "2015-08-06",
"comments" : "Some comments"
}
]
}, {
"name" : "Mary Smith",
"time" : "10:00:00",
"claim" : [{
"date" : "2015-08-06",
"comments" : "Some comments"
}
]
}
]
}
and your code like this
#Override
protected void onPostExecute(JSONObject json)
{
if (dialog.isShowing()) {
dialog.dismiss();
}
try
{
// Getting JSON Array from URL
JSONArray android = json.getJSONArray(TAG_RESULTS);
for (int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
// Storing JSON items in Variables
String time = c.getString(TAG_TIME);
String time = c.getString("name");
// for claims object:
JSONArray claims = c.getJSONArray(TAG_CLAIM);
for (int j = 0; j < claims.length(); j++) {
JSONObject d = claims.getJSONObject(j);
String date= d.getString("date");
String comments= d.getString("comments");
//other parsing and list view.
}
}
}
catch(Exception e){}
}

Related

Json data parse into table in java transformation in informatica developer

I have data in below format-
{
"result": [
{
"number": "C12",
"name": "ABC"
},
{
"number": "D12",
"name": "BCD"
},
{
"number": "E56",
"name": "fm"
}]
}
My code is -
String result = //that store my above json data;
try{
String jsonString = result;
JSONObject obj = new JSONObject(jsonString);
JSONArray arr = obj.getJSONArray("result");
for (int i = 0; i < arr.length(); i++)
{
String num = arr.getJSONObject(i).getString("number");
String name= arr.getJSONObject(i).getString("name");
generateRow();
}
}
catch(Exception e)
{
e.printStackTrace();
}
But with this code i am able to read only first record.
Please help in writing the code where i can read all the records.
You can move to Informatica developer tool in case you have the license and use H2R transformation

how to covert JSONObject to another Required JSONObect by mapping AccountId using java

**My result of JSONObject to convert as follows bellow code and have searched for many this how to convert using java but I converted that **
{
"result": {
"accountnames": [{
"accountName": "Hari",
"accountId": 878488
}, {
"accountName": "ravi",
"accountId": 878487
}],
"sales": [{
"accountSales": "89",
"accountId": 878488
}, {
"accountName": "98",
"accountId": 878487
}],
"countResult": [{
"accountResult": "945",
"accountId": 878488
}, {
"accountResult": "9452",
"accountId": 878489
}]
}
}
*and this is where the sample code to be converted *
{
"result": [{
"accountName": "Hari",
"accountSales": "89",
"accountResult": "945",
"accountId": 878488
},
{
"accountName": "ravi",
"accountSales": "98",
"accountId": 878487
},
{
"accountResult": "9452",
"accountId": 878489
}
]
}
My required JSON data has to be formatted as below
You need to group all the elements by accountId. You can use something like this depending on the json library that you are using.
Initialize the json object:
JSONObject rootJson = new JSONObject(json);
JSONObject resultJson = rootJson.getJSONObject("result");
Create a map to hold the objects by accountId:
Map<String, JSONObject> accountIds = new HashMap<>();
Then iterate for each key in the json, then for each element in the arrays and then for each property of the object inside the json:
Iterator mainKeys = resultJson.keys();
while (mainKeys.hasNext()) {
String key = (String) mainKeys.next();
JSONArray array = resultJson.getJSONArray(key);
for (int index = 0; index < array.length(); index++) {
JSONObject object = array.getJSONObject(index);
if (object.has("accountId")) {
String accountId = object.get("accountId").toString();
JSONObject accum = accountIds
.computeIfAbsent(accountId, (k) -> new JSONObject());
// depending on the json impl you can use putAll or similar
Iterator objKeys = object.keys();
while (objKeys.hasNext()) {
String property = (String) objKeys.next();
accum.put(property, object.get(property));
}
} else {
// does not have account id, ignore or throw
}
}
}
Finally create the json file and add the elements to the JSONArray:
JSONObject finalJson = new JSONObject();
finalJson.put("result", new JSONArray(accountIds.values()));
System.out.println(finalJson.toString());
(note: the json has an error in sales array accountName instead of accountSales)

JSON to JSON Transform of input sample using any existing java library/tools

Input:
{
"Student": {
"name" :"abc",
"id" : 588,
"class : "12"
}
}
Reqired Output:
{
"Student": {
"key" :"name",
"value":"abc",
"key" :"id",
"value":"588",
"key" :"class",
"value":"12"
}
}
Your output json invalid. Json object can not duplicate key .
You can use the library org.json and do something like this:
JSONObject jsonObject = new JSONObject(inputJson);
JSONObject outputJson = new JSONObject();
JSONArray array = new JSONArray();
for (Object key : jsonObject.keySet()) {
JSONObject item = new JSONObject();
String keyStr = (String)key;
Object keyvalue = jsonObj.get(keyStr);
item.put(keyStr, keyvalue);
array.put(item);
}
outputJson.put("Student", array);
System.out.println(json.toString());
Output :
{
"Student": [
{
"key": "name",
"value": "abc"
},
{
"key": "id",
"value": "588"
},
{
"key": "class",
"value": "12"
}
]
}
Similar to the other answer, the desired output JSON format is not valid.
The closest valid output would be
{
"Student" : [ {
"key" : "name",
"value" : "abc"
}, {
"key" : "id",
"value" : 588
}, {
"key" : "class",
"value" : "12"
} ]
}
This can be generated via Jolt with the following spec
[
{
"operation": "shift",
"spec": {
"Student": {
"name": {
"$": "Student[0].key",
"#": "Student[0].value"
},
"id": {
"$": "Student[1].key",
"#": "Student[1].value"
},
"class": {
"$": "Student[2].key",
"#": "Student[2].value"
}
}
}
}
]
This is easy to solve with JSLT if we assume the output is made valid JSON by making an array of key/value objects like the other respondents do.
The array function converts an object into an array of key/value objects exactly like you ask for, so the transform becomes:
{"Student" : array(.Student)}

How to decode JSONObject

This question is related with my previous question
I can successfully get the String in json format from the URL to my spring controller
Now I have to decode it
so I did like the following
#RequestMapping("/saveName")
#ResponseBody
public String saveName(String acc)
{jsonObject = new JSONObject();
try
{
System.out.println(acc);
org.json.JSONObject convertJSON=new org.json.JSONObject(acc);
org.json.JSONObject newJSON = convertJSON.getJSONObject("nameservice");
System.out.println(newJSON.toString());
convertJSON = new org.json.JSONObject(newJSON.toString());
System.out.println(jsonObject.getString("id"));
}
catch(Exception e)
{
e.printStackTrace();jsonObject.accumulate("result", "Error Occured ");
}
return jsonObject.toString();
}
This is the JSON String { "nameservice": [ { "id": 7413, "name": "ask" }, { "id": 7414, "name": "josn" }, { "id": 7415, "name": "john" }, { "id": 7418, "name": "RjhjhjR" } ] }
When I run the code then I get the error
org.json.JSONException: JSONObject["nameservice"] is not a JSONObject.
What wrong I am doing?
It's not a JSONObject, it's a JSONArray
From your question:
{ "nameservice": [ { "id": 7413, "name": "ask" }, { "id": 7414, "name": "josn" }, { "id": 7415, "name": "john" }, { "id": 7418, "name": "RjhjhjR" } ] }
The [ after the nameservice key tells you it's an array. It'd need to be a { to indicate an object, but it isn't
So, change your code to use it as a JSONArray, then iterate over the contents of that to get the JSONObjects inside it, eg
JSONArray nameservice = convertJSON.getJSONArray("nameservice");
for (int i=0; i<nameservice.length(); i++) {
JSONObject details = nameservice.getJSONObject(i);
// process the object here, eg
System.out.println("ID is " + details.get("id"));
System.out.println("Name is " + details.get("name"));
}
See the JSONArray javadocs for more details
It seems you're trying to get a JSONObject when "nameservice" is an array of JSONObjects and not an object itself. You should try this:
JSONObject json = new JSONObject(acc);
JSONArray jsonarr = json.getJSONArray("nameservice");
for (int i = 0; i < jsonarr.length(); i++) {
JSONObject nameservice = jsonarr.getJSONObject(i);
String id = nameservice.getString("id");
String name = nameservice.getString("name");
}
I don't understand why you do it manualy if you already have Spring Framework.
Take a look at MappingJackson2HttpMessageConverter and configure your ServletDispatcher accordingly. Spring will automatically convert your objects to JSON string and vice versa.
After that your controller method will be looked like:
#RequestMapping("/saveName")
#ResponseBody
public Object saveName(#RequestBody SomeObject obj) {
SomeObject newObj = doSomething(obj);
return newObj;
}

Problems parsing JSON in Java

I have this json:
[{
"name": "prog 1",
"show": [{
"name": "n1",
"time": "01.10 "
}, {
"name": "n2",
"time": "01.35 "
}]
}, {
"name": "prog 2",
"show": [{
"name": "n1",
"time": "01.10 "
}, {
"name": "n2",
"time": "01.35 "
}]
}]
Now trying to parse it in Java like:
JSONObject json=new JSONObject(json_str);
throws an Exception, since it doesn't begin with {, but [ since it's an array. I can parse this without problem in js, but aparently I cannot load an JSONArray with this string...
use: JSONArray objArray = new JSONArray (json_str);
// to access the individual objects inside the array:
for(int i=0;i<objArray.length();i++)
{
JSONObject obj = objArray.getJSONObject(i);
}
Have you tried this:
JSONArray arr = new JSONArray(stringWithContent);
Then access it like :
for(int i = 0; i<arr.length();i++){
System.out.println(arr.get(i));
}
You can try following code
JSONObject jObject = new JSONObject(json_str);
JSONArray array = jObject.getJSONArray("show");
for(int i = 0 ; i < array.length() ; i++)
{
System.out.println(array.getJSONObject(i).getString("name"));
System.out.println(array.getJSONObject(i).getString("time"));
}
It will helpful ...

Categories