I'm new to using JSON in Android and have been running into a few problems creating a model object from the JSON. If anyone knows of any good tutorials or resources that would be good to look into for more details I'd really appreciate them. I've been looking at the tutorial on Vogella and in the Bignerdranch Android book thus far.
I'm able to pull in the JSON and create a JSONobject, however my surveys aren't saving.
Here's the JSON I'm trying to parse:
[
{
"title": "Pepsi or Coke?",
"id": 1,
"questions": [
{
"id": 1,
"title": "Which pop do you prefer?",
"single_response": true,
"answers": [
{
"title": "Pepsi",
"id": 1
},
{
"title": "Coke",
"id": 2
},
{
"title": "Mountain Dew",
"id": 3
}
]
},
{
"id": 2,
"title": "What's your age?",
"single_response": true,
"answers": [
{
"title": "18-24",
"id": 4
},
{
"title": "25-34",
"id": 5
},
{
"title": "35-50",
"id": 6
},
{
"title": "50+",
"id": 7
}
]
},
{
"id": 3,
"title": "What's your political association?",
"single_response": true,
"answers": [
{
"title": "Republican",
"id": 8
},
{
"title": "Democrat",
"id": 9
}
]
}
]
}
]
I'm retrieving the json like this:
byte[] getUrlBytes(String urlSpec) throws IOException {
URL url = new URL(urlSpec);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
InputStream in = connection.getInputStream();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return null;
}
int bytesRead = 0;
byte[] buffer = new byte[1024];
while ((bytesRead = in.read(buffer)) > 0) {
out.write(buffer, 0, bytesRead);
}
out.close();
return out.toByteArray();
} finally {
connection.disconnect();
}
}
public String getUrl(String urlSpec) throws IOException {
return new String(getUrlBytes(urlSpec));
}
And here's where I parse it:
public ArrayList<Survey> getSurveys(String apiKey) throws JSONException {
ArrayList<Survey> surveys = new ArrayList<Survey>();
try {
String url = Uri.parse(ENDPOINT).buildUpon().appendQueryParameter("auth_token", apiKey).build().toString();
String jsonString = getUrl(url);
Log.i(TAG, "Received json string: " + jsonString);
try {
JSONArray array = new JSONArray(jsonString);
for (int i = 0; i < array.length(); i ++) {
JSONObject object = array.getJSONObject(i);
Log.i(TAG, "Object is: " + object.toString());
}
for (int i = 0; i < array.length(); i++) {
Survey survey = new Survey(array.getJSONObject(i));
surveys.add(survey);
Log.i(TAG, "Survey is: " + survey.toString());
}
} catch (Exception e) {
Log.e(TAG, "Survey didn't save");
}
} catch (IOException ioe) {
Log.e(TAG, "Failed to retrieve surveys: " + ioe);
}
return surveys;
}
I'm assuming that the issue is in my create survey method itself since the JSONobjects are created correctly, but the surveys aren't saving. Any idea where I'm going wrong?
public Survey(JSONObject json) throws JSONException {
mId = UUID.fromString(json.getString("id"));
if (json.has("title")) {
mTitle = json.getString("title");
}
}
As always any help is very much appreciated!
Turns out the problem was that I was trying to convert the int id that was getting sent in JSON to a UUID.
As long as the data types match up the items are created correctly.
Related
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"
}
]
}
I'm trying to read data from this API: http://events.makeable.dk/api/getEvents with the AsyncTask method which Is first time I try this. I'm trying to only read all TITLES from the API, but I'm not getting any titles.
Instead I get this exception: W/System.err: org.json.JSONException: (...)
Which shows me the whole API.
I have put Log.d(); around my code and I can se that my code never do or reach something in onPostExecute(String s) and thats is maybe why I never get any TITLES.
The many examples on the web of how to do this is so different from eachother and makes this very frustrating to solve!
private class JsonParser extends AsyncTask<String, Void, String> {
HttpURLConnection conn;
URL url = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(MainActivity.this, "LOADING DATA FROM API", Toast.LENGTH_SHORT).show();
}
#Override
protected String doInBackground(String... params) {
try{
url = new URL(URL);
conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.setDoOutput(true);
if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){
InputStream inputStream = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine())!= null){
result.append(line);
}
return (result.toString());
}
}catch (MalformedURLException e){
e.printStackTrace();
}catch (Exception ee){
ee.printStackTrace();
}
return "";
}
#Override
protected void onPostExecute(String s) {
//------ never comes below this area //-----------
try{
JSONArray jsonArray = new JSONArray(s);
for(int i =0; i<jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
Log.d("TAG", "JSON: " + jsonObject.getString("TITLE"));
}
}catch (Exception e){
e.printStackTrace();
}
}
}
I viewed your API's response at this Website. It is a JSON Object because it is started by an open curly brace {. So therefore use JSONObject first.
The response looks like this:
{
"success": true,
"message": "548 events returned successfully",
"last_change": 1459515263,
"events": [
{
"category": "Musik",
"category_id": "75",
"datelist": [
{
"start": 1436536800,
"end": 1436544000
}
],
"description": "",
"description_english": "",
"description_german": "",
"eventgroup": "",
"eventid": "55815f7fe714a",
"family_friendly": "0",
"last_updated": 1436166668,
"location_address": "Klostertorv 1",
"location_city": "Århus C",
"location_id": "1593",
"location_latitude": 56.158092,
"location_longitude": 10.206756,
"location_name": "Klostertorv",
"location_postcode": "8000",
"organizer_email": "",
"organizer_name": "Café Smagløs ",
"organizer_phone": "",
"picture_name": "http://www.jazzfest.dk/img/photos_big/tcha-badjo---strings-og-buttons.jpg",
"price": "-1",
"subcategory": "Musik",
"subcategory_id": "84",
"subtitle": "",
"subtitle_english": "",
"subtitle_german": "",
"tags": "Swing/Mainstream",
"tickets_url": "",
"title": "Tcha Badjo + Strings & Buttons KONCERT AFLYST",
"title_english": "Tcha Badjo + Strings & Buttons CONCERT CANCELLED",
"title_german": "Tcha Badjo + Strings & Buttons CONCERT CANCELLED",
"url": "http://www.jazzfest.dk/?a=reviews&lang=&kryds_id=2122&y=2015",
"user_id": "23",
"video_url": ""
}]
}
So therefore it is:
try {
JSONObject object = new JSONObject(s);
JSONArray events = object.getJSONArray("events");
int evSize = events.length();
for (int x = 0; x < evSize; x++) {
JSONObject object1 = events.getJSONObject(x);
String title = object1.getString("title");
}
} catch (JSONException e) {
e.printStackTrace();
}
I got the json data using this
``
private void loadQuestions() throws Exception {
try {
InputStream questions = this.getBaseContext().getResources()
.openRawResource(R.raw.questions);
bReader = new BufferedReader(new InputStreamReader(questions));
StringBuilder quesString = new StringBuilder();
String aJsonLine = null;
while ((aJsonLine = bReader.readLine()) != null) {
quesString.append(aJsonLine);
}
Log.d(this.getClass().toString(), quesString.toString());
JSONObject quesObj = new JSONObject(quesString.toString());
quesList = quesObj.getJSONArray("Questions");
Log.d(this.getClass().getName(),
"Num Questions " + quesList.length());
} catch (Exception e){
} finally {
try {
bReader.close();
} catch (Exception e) {
Log.e("", e.getMessage().toString(), e.getCause());
}
}
}
public static JSONArray getQuesList() {
return quesList;
}
``
Here is the json data.
``
{
"Questions": [
{
"Question": "Which animal is Carnivorous?",
"CorrectAnswer": 1,
"Answers": [
{
"Answer": "Cow"
},
{
"Answer": "Lion"
},
{
"Answer": "Goat"
},
{
"Answer": "Elephant"
}
]
},
{
"Question": "Humans need",
"CorrectAnswer": 0,
"Answers": [
{
"Answer": "Oxygen"
},
{
"Answer": "Nitrogen"
},
{
"Answer": "CarbonDioxide"
},
{
"Answer": "Hydrogen"
}
]
},
{
"Question": "Choose the Amphibian ",
"CorrectAnswer": 0,
"Answers": [
{
"Answer": "Frog"
},
{
"Answer": "Owl"
},
{
"Answer": "Goat"
},
{
"Answer": "Fox"
}
]
},
{
"Question": "---- is part of Earth`s Atmosphere.",
"CorrectAnswer": 1,
"Answers": [
{
"Answer": "Unisphere"
},
{
"Answer": "Troposphere"
},
{
"Answer": "Oxysphere"
},
{
"Answer": "Carbosphere"
}
]
},
]
}
After getting the json data
All I need now is to randomize it.
Help a brother please, I have tried everything but nothing is working
Thanks in advance
After
quesList = quesObj.getJSONArray("Questions"); // Right place to shuffle PeterOla,add this to randomize questions list:
List<JSONObject> questionsList = new ArrayList<JSONObject>(quesList.length());
for(int i=0,size=quesList.length();i<size;++i){
try {
questionsList.add(quesList.getJSONObject(i));
} catch (JSONException e) {
e.printStackTrace();
}
}
long seed = System.nanoTime();
Collections.shuffle(questionsList, new Random(seed));
Put values into a list, then you can shuffle it easily. Use this:
ArrayList<String> listdata = new ArrayList<String>();
JSONArray jArray = (JSONArray)jsonObject;
if (jArray != null) {
for (int i=0;i<jArray.length();i++){
listdata.add(jArray.get(i).toString());
}
}
Collections.shuffle(listdata);
try {
JSONObject jsonObject = new JSONObject(response);
String current_page = jsonObject.optString("current_page");
NextPageUrl = jsonObject.optString("next_page_url");
if (current_page.equals("1")){
lifeHomeModels.clear();
JSONArray data = jsonObject.getJSONArray("data");
for (int i =0;i<data.length();i++){
JSONObject jsonObject1 = data.getJSONObject(i);
String id = jsonObject1.optString("id");
String post_user_id = jsonObject1.optString("user_id");
String post_id = jsonObject1.optString("post_id");
String post_details = jsonObject1.optString("post_details");
}
Family_HomeModel inputModel = new Family_HomeModel();
inputModel.setId(id);
inputModel.setPost_user_id(post_user_id);
inputModel.setPost_id(post_id);
inputModel.setPost_details(post_details);
lifeHomeModels.add(inputModel);
}
long seed = System.nanoTime();
Collections.shuffle(lifeHomeModels, new Random(seed));
}
lifeHomeAdapter.notifyDataSetChanged();
}
catch (JSONException e) {
e.printStackTrace();
}
My app is crashing when trying to parse Instagram JSON. What am I doing wrong here?
public class InstagramActivity extends BaseActivity {
static String url;
static ArrayList<String> thumbnailURLS;
static ArrayList<String> standardURLS;
static Context context;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grid);
context = getApplicationContext();
getActionBar().setTitle("Instagram");
url = "https://api.instagram.com/v1/users/1373666362/media/recent/?client_id=a2b04732b52d43c99fe453a8ca2a5512&count=50";
thumbnailURLS = new ArrayList<String>();
standardURLS = new ArrayList<String>();
new ParseJSON().execute();
}
public static class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser()
{
}
public JSONObject getJSONFromUrl(String jsonUrl)
{
// Making HTTP request
try
{
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(jsonUrl);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
json = sb.toString();
}
catch (Exception e)
{
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try to parse the string to a JSON object
try
{
jObj = new JSONObject(json);
}
catch (JSONException e)
{
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
public static class ParseJSON extends AsyncTask<Void,Void,ArrayList> {
#Override
protected void onPreExecute()
{
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected ArrayList doInBackground(Void... params) {
JSONParser jParser = new JSONParser();
// get json from url here
JSONObject json = jParser.getJSONFromUrl(url);
try {
JSONArray dataArray = json.getJSONArray("data");
int thumbnailsCount = dataArray.length();
for (int i = 0; i < thumbnailsCount; i++) {
JSONObject imagesObject = dataArray.getJSONObject(i).getJSONObject("images");
String thumbURL = imagesObject.getJSONObject("thumbnail").getString("url");
thumbnailURLS.add(thumbURL);
}
}
catch (Exception e) {
e.getMessage().toString();
}
return thumbnailURLS;
}
#Override
protected void onPostExecute(ArrayList result) {
super.onPostExecute(result);
for (String thumb : thumbnailURLS) {
System.out.println(thumb);
}
}
}
}
It catches a JSONException
E/JSON Parser﹕ Error parsing data org.json.JSONException: End of input at character 0 of
and
E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #2
This is NULL. JSONObject json = jParser.getJSONFromUrl(url);
Here is some of the expected JSON.
{
"pagination": {
"next_url": "https://api.instagram.com/v1/users/1373666362/media/recent?access_token=25320296.1fb234f.b797e861c2494059b6584ac9749208fe&count=2&max_id=791341826737262101_1373666362",
"next_max_id": "791341826737262101_1373666362"
},
"meta": {
"code": 200
},
"data": [
{
"attribution": null,
"tags": [
"kystatefair"
],
"type": "image",
"location": null,
"comments": {
"count": 0,
"data": []
},
"filter": "Amaro",
"created_time": "1408648864",
"link": "http://instagram.com/p/r-MuYWFU96/",
"likes": {
"count": 5,
"data": [
{
"username": "tayworthington_",
"profile_picture": "http://photos-g.ak.instagram.com/hphotos-ak-xaf1/10632550_835588266460870_765781001_a.jpg",
"id": "24471760",
"full_name": "τᎯϓιΘર"
},
{
"username": "renee_laurent",
"profile_picture": "http://images.ak.instagram.com/profiles/profile_407687505_75sq_1397913189.jpg",
"id": "407687505",
"full_name": "Renee Laurent"
},
{
"username": "kystatefair",
"profile_picture": "http://images.ak.instagram.com/profiles/profile_381460857_75sq_1396983015.jpg",
"id": "381460857",
"full_name": "kystatefair"
},
{
"username": "jennaharrod1",
"profile_picture": "http://photos-b.ak.instagram.com/hphotos-ak-xfa1/10665605_1495839117327497_809128971_a.jpg",
"id": "18591399",
"full_name": "Jenna Harrod"
}
]
},
"images": {
"low_resolution": {
"url": "http://scontent-a.cdninstagram.com/hphotos-xaf1/t51.2885-15/10598650_352432021574566_306460147_a.jpg",
"width": 306,
"height": 306
},
"thumbnail": {
"url": "http://scontent-a.cdninstagram.com/hphotos-xaf1/t51.2885-15/10598650_352432021574566_306460147_s.jpg",
"width": 150,
"height": 150
},
"standard_resolution": {
"url": "http://scontent-a.cdninstagram.com/hphotos-xaf1/t51.2885-15/10598650_352432021574566_306460147_n.jpg",
"width": 640,
"height": 640
}
},
"users_in_photo": [],
"caption": {
"created_time": "1408648864",
"text": "Congratulations to The Lindsey Family for winning the Gospel Quartet competition! #kystatefair",
"from": {
"username": "kyfarmbureau",
"profile_picture": "http://photos-b.ak.instagram.com/hphotos-ak-xpf1/10349740_650479825030913_1755233568_a.jpg",
"id": "1373666362",
"full_name": "Kentucky Farm Bureau"
},
"id": "792126548887293629"
},
"user_has_liked": false,
"id": "792126548258148218_1373666362",
"user": {
"username": "kyfarmbureau",
"website": "",
"profile_picture": "http://photos-b.ak.instagram.com/hphotos-ak-xpf1/10349740_650479825030913_1755233568_a.jpg",
"full_name": "Kentucky Farm Bureau",
"bio": "",
"id": "1373666362"
}
},
{
"attribution": null,
"tags": [
"kfbmtc"
],
"type": "image",
"location": null,
"comments": {
"count": 0,
"data": []
},
"filter": "Normal",
"created_time": "1408555318",
"link": "http://instagram.com/p/r7aTLelU4V/",
"likes": {
"count": 4,
"data": [
{
"username": "corkey_cole",
"profile_picture": "http://photos-e.ak.instagram.com/hphotos-ak-xaf1/10598220_490230854445140_2139881142_a.jpg",
"id": "324166968",
"full_name": "corkey_cole"
},
{
"username": "renee_laurent",
"profile_picture": "http://images.ak.instagram.com/profiles/profile_407687505_75sq_1397913189.jpg",
"id": "407687505",
"full_name": "Renee Laurent"
},
{
"username": "silveradomafia04",
"profile_picture": "http://photos-e.ak.instagram.com/hphotos-ak-xfa1/914483_1500860143488988_1771984176_a.jpg",
"id": "1006562558",
"full_name": "Gideon Bailey"
},
{
"username": "sharelouisville",
"profile_picture": "http://images.ak.instagram.com/profiles/profile_1302605134_75sq_1399019203.jpg",
"id": "1302605134",
"full_name": "Share Louisville"
}
]
},
"images": {
"low_resolution": {
"url": "http://scontent-a.cdninstagram.com/hphotos-xaf1/t51.2885-15/10598436_1456586981280578_133918080_a.jpg",
"width": 306,
"height": 306
},
"thumbnail": {
"url": "http://scontent-a.cdninstagram.com/hphotos-xaf1/t51.2885-15/10598436_1456586981280578_133918080_s.jpg",
"width": 150,
"height": 150
},
"standard_resolution": {
"url": "http://scontent-a.cdninstagram.com/hphotos-xaf1/t51.2885-15/10598436_1456586981280578_133918080_n.jpg",
"width": 640,
"height": 640
}
},
"users_in_photo": [],
"caption": {
"created_time": "1408555318",
"text": "Media is starting to crowd around for #kfbmtc",
"from": {
"username": "kyfarmbureau",
"profile_picture": "http://photos-b.ak.instagram.com/hphotos-ak-xpf1/10349740_650479825030913_1755233568_a.jpg",
"id": "1373666362",
"full_name": "Kentucky Farm Bureau"
},
"id": "791341827391573199"
},
"user_has_liked": false,
"id": "791341826737262101_1373666362",
"user": {
"username": "kyfarmbureau",
"website": "",
"profile_picture": "http://photos-b.ak.instagram.com/hphotos-ak-xpf1/10349740_650479825030913_1755233568_a.jpg",
"full_name": "Kentucky Farm Bureau",
"bio": "",
"id": "1373666362"
}
}
]
}
UPDATE: The problem appears to be with the Instagram api url I'm using isn't giving me the JSON. I think it may be because I'm using my client_id instead of getting an access token. Does anyone know if that is the case? I used a JSON URL from something else that I know doesn't require an access token and it returned the JSON just fine.
I have updated your method getJSONFromUrl, which can be seen below:
The problem is that, the server is returning 405 means method not allowed. You was using POST to access the data, which this server does not allow. You have to use GET here for a successful request.
Rest of your code is working fine.
You can update the code below to add a default case where you can return a valid constant json string with a message that can avoid app crash, as well you can add other cases like 404 and 405 and return a valid json with an appropriate message that is suitable to the user to understand.
public JSONObject getJSONFromUrl(String jsonUrl)
{
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(jsonUrl);
String responseBody = "DEFAULT_MSG_TEXT";
int resCode = 0;
try{
HttpResponse response = client.execute(get);
int responseCode = response.getStatusLine().getStatusCode();
resCode = responseCode;
switch(responseCode) {
case 200:
HttpEntity entity = response.getEntity();
if(entity != null) {
responseBody = EntityUtils.toString(entity);
}
break;
}
}
catch(Exception ex){
Log.e("Post Error",resCode + "\n Exception" + ex);
responseBody = "DEFAULT_MSG_TEXT";
}
json = responseBody;
// try to parse the string to a JSON object
try
{
jObj = new JSONObject(json);
}
catch (JSONException e)
{
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
Try this and let me know !!!
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");