Nested JSON arrays - android

I am parsing some JSON that has arrays within arrays, and I just cant seem to get the data of the arrays within the first array.
My JSON looks like this (I cut it off in the end so it wasn't that long):
{"TrackingInformationResponse": {
"shipments": [
{
"shipmentId": "03015035146308",
"uri": "\/ntt-service-rest\/api\/shipment\/03015035146308\/0",
"assessedNumberOfItems": 1,
"deliveryDate": "2013-05-13T11:47:00",
"estimatedTimeOfArrival": "2013-05-13T16:00:00",
"service": {
"code": "88",
"name": "DPD"
},
"consignor": {
"name": "Webhallen Danmark ApS",
"address": {
"street1": "Elsa Brändströms Gata 52",
"city": "HÄGERSTEN",
"countryCode": "SWE",
"country": "Sverige",
"postCode": "12952"
}
},
"consignee": {
"name": "Lene Bjerre Kontor & IT Service",
"address": {
"street1": "Lene Bjerre",
"street2": "Ørbækvej 8, Hoven",
"city": "TARM",
"countryCode": "???",
"postCode": "6880"
}
},
"statusText": {
"header": "Forsendelsen er udleveret",
"body": "Forsendelsen blev leveret 13-05-2013 kl. 11:47"
},
"status": "DELIVERED",
"totalWeight": {
"value": "0.55",
"unit": "kg"
},
"totalVolume": {
"value": "0.005",
"unit": "m3"
},
"items": [
{
"itemId": "03015035146308",
"dropOffDate": "2013-05-08T17:18:00",
"deliveryDate": "2013-05-13T11:47:00",
"status": "DELIVERED",
"statusText": {
"header": "Forsendelsen er udleveret til modtageren",
"body": "Forsendelsen blev udleveret 13-05-2013 kl. 11:47"
},
I can get the content of the "shipments" array just fine, but I have no idea how to get the contents of the "items" array. My code looks like this:
try {
JSONObject jsonObject = new JSONObject(result);
JSONObject TrackingInformationResponse = new JSONObject(jsonObject.getString("TrackingInformationResponse"));
JSONArray shipments = new JSONArray(TrackingInformationResponse.getString("shipments"));
for (int i = 0; i < shipments.length(); i++) {
JSONObject JSONitems = shipments.getJSONObject(i);
String shipmentId = JSONitems.getString("shipmentId");
//do stuff
}
} catch (Exception e) {
Log.d("ReadWeatherJSONFeedTask", e.getLocalizedMessage());
}
How would I do the same with the "items" array as I did with the "shipments" array?

You have to get the items array from inside the Shipment array, like you did the shipments, then iterate through that, like you did the shipments.
It might look something like:
JSONObject jsonObject = new JSONObject(result);
JSONObject TrackingInformationResponse = new JSONObject(jsonObject.getString("TrackingInformationResponse"));
JSONArray shipments = new JSONArray(TrackingInformationResponse.getString("shipments"));
for (int i = 0; i < shipments.length(); i++) {
JSONObject JSONitems = shipments.getJSONObject(i);
String shipmentId = JSONitems.getString("shipmentId");
JSONArray items = new JSONArray(JSONitems.getString("items");
//get items stuff
//do stuff
}
} catch (Exception e) {
Log.d("ReadWeatherJSONFeedTask", e.getLocalizedMessage());
}

items is a JSON Array located inside the shipments array, so you need to get the items array within the shipments, maybe like this :
for (int i = 0; i < shipments.length(); i++) {
JSONObject JSONitems = shipments.getJSONObject(i);
String shipmentId = JSONitems.getString("shipmentId");
JSONArray items = new JSONArray(JSONitems.getString("items"));
//iterate over items
}
Hope this helps, Good luck

Try bellow code:
JSONObject jObject = new JSONObject(yourJSONString);
JSONObject trackInfo = jObject.getJSONObject("TrackingInformationResponse");
JSONArray shipMents = trackInfo.getJSONArray("shipments");
JSONArray items = shipMents.getJSONArray("items");

Related

looping through nested json array is adding previously assigned value to data model

please look into this json:
{
"data": [
{
"date": "Thursday 1, August, 2019",
"time": [
{
"times": "1:13PM to 1:13PM",
"notice": "testing",
"category": "Meeting"
},
{
"times": "12:00PM to 1:00PM",
"notice": "Meeting",
"category": "Meeting"
}
]
},
{
"date": "Friday 2, August, 2019",
"time": [
{
"times": "3:00PM to 3:30PM",
"notice": "Appointment",
"category": "Meeting"
},
{
"times": "12:00PM to 12:30PM",
"notice": "Appointment",
"category": "Meeting"
}
]
},
{
"date": "Monday 5, August, 2019",
"time": [
{
"times": "11:00AM to 11:30AM",
"notice": "Obj",
"category": "Meeting"
}
]
}
]
}
I'm polulating this json data to my ArrayList like this:
VipPojo playerModel;
try {
JSONArray dataArray = obj.getJSONArray("data");
for (int i = 0; i < dataArray.length(); i++) {
JSONObject dataobj = dataArray.getJSONObject(i);
JSONArray dataArrays1 = dataobj.getJSONArray("time");
String date = dataobj.getString("date");
System.out.println("date: " + date); // here I get correct data (all 3 items);
for (int j = 0; j < dataArrays1.length(); j++) {
playerModel = new VipPojo();
JSONObject dataobj1 = dataArrays1.getJSONObject(j);
playerModel.setDate(date); // this is adding same previous assigned "date" until loop ends(I get 5 data with duplicate values)
playerModel.setTimes(dataobj1.getString("times"));
playerModel.setNotice(dataobj1.getString("notice"));
playerModel.setCategory(dataobj1.getString("category"));
dataModelArrayList.add(playerModel);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
as I mentioned in comments in code above, "date" object is adding previously assigned value to data model since setDate() is being used inside the inner loop which I don't want that.
Can you help me with this please?
use Gson library Get nested JSON object with GSON using retrofit
for nested object use an object in itself
for more information https://futurestud.io/tutorials/gson-mapping-of-nested-objects
Change
playerModel.setDate(dataobj.getString("date"));
to
playerModel.setDate(date);
isn't "date" field static in VipPojo
you can try like this
VipPojo playerModel;
try {
JSONArray dataArray = obj.getJSONArray("data");
for (int i = 0; i < dataArray.length(); i++) {
playerModel = new VipPojo();
JSONObject dataobj = dataArray.getJSONObject(i);
JSONArray dataArrays1 = dataobj.getJSONArray("time");
String date = dataobj.getString("date");
System.out.println("date: " + date); // here I get correct data (all 3 items);
playerModel.setDate(date);
for (int j = 0; j < dataArrays1.length(); j++) {
JSONObject dataobj1 = dataArrays1.getJSONObject(j);
// this is adding same previous assigned "date" until loop ends(I get 5 data with duplicate values)
playerModel.setTimes(dataobj1.getString("times"));
playerModel.setNotice(dataobj1.getString("notice"));
playerModel.setCategory(dataobj1.getString("category"));
dataModelArrayList.add(playerModel);
}
}
} catch (JSONException e) {
e.printStackTrace();
}

Reading data from a json file in Android and put it in an array

if i have a json file like that
{
"users": [{
"name": "aa",
"address": "a"
},
{
"name ": "bb",
"address": "b"
},
{
"name": "cc",
"address": "c"
},
]}
how to read this json file and put all names in a String array in android
i used this code but in second loop it catches exception
public void loadJSONFromAsset() {
String json = null;
try {
InputStream is = getAssets().open("data.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
}
try {
JSONObject obj = new JSONObject(json);
JSONArray m_jArry = obj.getJSONArray("users");
for (int i = 0; i < m_jArry.length(); i++) {
JSONObject jo_inside = m_jArry.getJSONObject(i);
names.add(jo_inside.getString("name"));
images.add(jo_inside.getString("address"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
That Json object 2nd element in the array has space next to name you can solve by 2 ways.
As your backend guys to change that
You solve the problem like this,
Change getString to optString like this
for (int i = 0; i < m_jArry.length(); i++) {
JSONObject jo_inside = m_jArry.getJSONObject(i);
String name = jo_inside.optString("name");
if(TextUtils.isEmpty(name)) {
name = jo_inside.optString("name "); // that object have space
}
names.add(name);
images.add(jo_inside.getString("address"));
}
Your Json file contain wrong format JSON.
Remove , from the last array element
{
"name": "cc",
"address": "c"
},
The valid Json should be:
{
"users": [{
"name": "aa",
"address": "a"
},
{
"name": "bb",
"address": "b"
},
{
"name": "cc",
"address": "c"
}
]
}
You have problem in your JSON string only. In second JSON name field has extra space. And also there is , after last JSON },
{
"users": [{
"name":"aa",
"address":"a"
},
{
"name":"bb",
"address":"b"
},
{
"name":"cc",
"address":"c"
}
]
}

How to get single object value and send to server

I have the following JSON response i want to get separate values like CHIL SEZ IT Park,Coimbatore,Tamil Nadu,India
JSON String is:
[
{
"value": "CHIL SEZ IT Park",
"offset": 0
},
{
"value": "Coimbatore",
"offset": 18
},
{
"value": "Tamil Nadu",
"offset": 30
},
{
"value": "India",
"offset": 42
}
]
Try this:
ArrayList<String> arrayList = new ArrayList<>();
try {
JSONArray jsonArray = new JSONArray(responseStr);
for(int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String value = jsonObject.getString("value");
arrayList.add(value);
}
} catch (JSONException e) {
e.printStackTrace();
}
Place this function and pass the jsonString. You will get the ArrayList from the JSON.
public ArrayList<String> getPlaceName(String jsonString){
ArrayList<String> places = new ArrayList<>();
try{
JSONArray array = new JSONArray(jsonString);
for(int x=0;x<array.length();x++){
places.add(array.getJSONObject(x).getString("value"));
}
}catch (JSONException e){}
return places;
}

Parsing json (android) [duplicate]

Before I parse json json array, but this json object. Its It drove me to a standstill. How i can parse json like this:
{ "test1": {
"1": {
"action": "0",
"type": "1",
"id": "1",
},
"2": {
"action": "0",
"type": "1",
"id": "2",
}
},
"test2": {
"1": {
"id": "1",
"name": "one"
},
"2": {
"id": "2",
"name": "two"
},
"5": {
"id": "5",
"name": "three"
}
}}
When you don't have a fixed set of keys, that you know upfront, the only way to parse it is to use keys(). It returns an Iterator with the keys contained in the JSONObject. In your case you could have
JSONObject jsonObject = new JSONObject(...);
Iterator<String> iterator = jsonObject.keys();
while(iterator.hasNext()) {
String currentKey = iterator.next();
JSONObject obj = jsonObject.optJSONObject(key);
if (obj != null) {
Iterator<String> iterator2 = obj.keys();
}
}
iterator will return test1 and test2, while iterator2 will return 1 and 2, for test1 and 1 ,2 , 5 for test2
You can create a JSONObject From string as bellow
JSONObject jsonObject = new JSONObject(YOUR_JSON_STRING);
and to parse the jsonObject
JSONObject test1Json = jsonObject.getJSONObject("test1");
JSONObject oneTest1Json = test1Json.getJSONObject("1");
to get String values
String action = oneTest1Json.getString("action");
String type = oneTest1Json.getString("type");
String id = oneTest1Json.getString("id");
Log.d("Json parse","action -"+action+" type -"+type+" id -"+id);
if need them as JSONArray the you can try
public JSONArray getJsonArray (JSONObject jsonObject){
JSONArray nameJsonArray = jsonObject.names();
JSONArray jsonArray = new JSONArray();
for (int i = 0; i < nameJsonArray.length(); i++) {
try {
String key = nameJsonArray.getString(i);
jsonArray.put(jsonObject.getString(key));
} catch (JSONException e) {
e.printStackTrace();
}
}
return jsonArray;
}
in case keys like test1,test2,test3...
JSONObject jsonObject = new JSONObject("{'test1':'Kasun', 'test2':'columbo','test3': '29'}");
JSONArray jsonArray = new JSONArray();
for (int i = 1; i <= jsonObject.names().length(); i++) {
try{
jsonArray.put(jsonObject.getString("test" + i));
}catch (JSONException e){
e.printStackTrace();
}
you can get your JSONArray this way.

Android Json parsing with complicated arrays

[
{
"countries": [
{
"id": 1,
"country": "India"
},
{
"id": 2,
"country": "Australia"
},
{
"id": 3,
"country": "Srilanka"
},
{
"id": 4,
"country": "Pakistan"
},
{
"id": 5,
"country": "Switzerland"
}
]
}
]
How to parse this Json Response in Android. i am not getting any proper solution.
please help me.
Do it like this...
JSONArray arr = locs.getJSONArray("countries");
for (int i = 0; i < arr.length(); ++i) {
JSONObject rec = arr.getJSONObject(i);
int id = rec.getInt("id");
String con = rec.getString("country");
// ...
}
JSONArray jArr=new JSONArray(response);
for(int i=0;i<jArr.length;i++)
{
id[]=jArr.getJSONObject(i).getInt("id");
con[]=jArr.getJSONObject(i).getString("country");
}
http://developer.android.com/reference/org/json/JSONTokener.html
I've also seen Jackson used in Android apps.
JSONArray countriesobj = new JSONArray();
JSONObject json;
try {
JSONObject jObject = new JSONObject(response);
json = jObject;
countriesobj = json.getJSONArray("countries");
country = new String[countriesobj.length()];
for (int i = 0; i < countriesobj.length(); i++) {
JSONObject e = countriesobj.getJSONObject(i);
country[i] = e.getString("country");
}
} catch (Exception e) {
e.printStackTrace();
}

Categories

Resources