I'm retrieving some JSON data from my server. Sometimes this can come in the form of a JSONObject (one objects) or a JSONArray (multiple objects). I'm aware of how to detect if it is an array or an object... but the problem is that detecting it means that I have to have two completely separate bits of logic, one for objects and one for arrays. It's a really unclean solution that I'm surprised is not asked about more often.
What I'd like to do is: if the JSON is a JSONObject (one object), then convert it to a JSONArray (with only one entry). Then I can proceed with my normal logic for interpreting JSONArrays.
My JSON would come in like this:
{
"Changes":
{
"Row":
{
"@ChangeId":"17192386","@Type":"U","@TableName":"Change","@PK":"g1fbb6c7-abcf-e741-846c-b499baf5845d","@ColList":"date"
},
"Data":
{
"@date":"22/05/2014 09:03:00"
}
}
}
Normally I have multiple records in the Row and Data objects. But in this instance, I have only one in each. My usual method is:
JSONObject jsonObj = new JSONObject(jsonString);
JSONObject changes = jsonObj.getJSONObject("Changes");
JSONArray arrChanges = changes.getJSONArray("Row");
JSONArray arrData = changes.getJSONArray("Data");
// Cycle through arrays here
This code will crash on the .getJSONArray("Row"); line.
To avoid this, after I have the changes object, I'd like to force the Row and Data objects into a JSONArray, even if there is only one value - like above, so I can continue with my normal logic. Is there a way to do this?
Use this method to convert JSONObject into JSONArray :
JSONObject jsonObj = new JSONObject(jsonString);
JSONObject changes = jsonObj.getJSONObject("Changes");
JSONArray arrChanges = covertJsonObjectToJsonArray(changes.get("Row"));
JSONArray arrData = covertJsonObjectToJsonArray(changes.get("Data"));
public JSONArray covertJsonObjectToJsonArray(Object InsideArray) {
JSONArray jsonArray;
if (InsideArray instanceof JSONArray) {
jsonArray = (JSONArray) InsideArray;
} else {
jsonArray = new JSONArray();
jsonArray.put((JSONObject) InsideArray);
}
return jsonArray;
}
If JSONArray is there then it will return JSONArray, and if JSONOject is there still it will return JSONArray.
if I understood correctly what your problem is:
JSONObject jsonObj = new JSONObject(jsonString);
JSONObject changes = jsonObj.getJSONObject("Changes");
JSONArray arrChanges = null;
JSONArray arrData = null;
if (isASingleJson) {
arrChanges = new JSONArray();
arrData = new JSONArray();
arrChanges.put(changes.getJSONObject("Row"));
arrData.put(changes.getJSONObject("Data"));
} else {
arrChanges = changes.getJSONArray("Row");
arrData = changes.getJSONArray("Data");
}
//logic to handle arrays here...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With