I want to get the lineId, destinationName and timeToStation from this api call https://api.tfl.gov.uk/Line/25,86,w19/Arrivals?stopPointId=490009219W&app_id=&app_key=
Can someone help with example please?
[
{
"$type": "Tfl.Api.Presentation.Entities.Prediction, Tfl.Api.Presentation.Entities",
"id": "-480785385",
"operationType": 1,
"vehicleId": "BJ11DSX",
"naptanId": "490009219W",
"stationName": "Little Ilford Lane",
"lineId": "25",
"lineName": "25",
"platformName": "B",
"direction": "inbound",
"bearing": "245",
"destinationNaptanId": "",
"destinationName": "Oxford Circus",
"timestamp": "2016-04-17T16:56:56.463Z",
"timeToStation": 1534,
"currentLocation": "",
"towards": "East Ham or Manor Park",
"expectedArrival": "2016-04-17T17:22:31Z",
"timeToLive": "2016-04-17T17:23:01Z",
"modeName": "bus"
},
{
"$type": "Tfl.Api.Presentation.Entities.Prediction, Tfl.Api.Presentation.Entities",
"id": "1992301652",
"operationType": 1,
"vehicleId": "BJ11DVA",
"naptanId": "490009219W",
"stationName": "Little Ilford Lane",
"lineId": "25",
"lineName": "25",
"platformName": "B",
"direction": "inbound",
"bearing": "245",
"destinationNaptanId": "",
"destinationName": "Oxford Circus",
"timestamp": "2016-04-17T16:56:56.463Z",
"timeToStation": 1159,
"currentLocation": "",
"towards": "East Ham or Manor Park",
"expectedArrival": "2016-04-17T17:16:16Z",
"timeToLive": "2016-04-17T17:16:46Z",
"modeName": "bus"
},
{
"$type": "Tfl.Api.Presentation.Entities.Prediction, Tfl.Api.Presentation.Entities",
"id": "733078946",
"operationType": 1,
"vehicleId": "BJ11DVG",
"naptanId": "490009219W",
"stationName": "Little Ilford Lane",
"lineId": "25",
"lineName": "25",
"platformName": "B",
"direction": "inbound",
"bearing": "245",
"destinationNaptanId": "",
"destinationName": "Oxford Circus",
"timestamp": "2016-04-17T16:56:56.463Z",
"timeToStation": 790,
"currentLocation": "",
"towards": "East Ham or Manor Park",
"expectedArrival": "2016-04-17T17:10:07Z",
"timeToLive": "2016-04-17T17:10:37Z",
"modeName": "bus"
}
]
My AsyncTask is given belw
#Override
protected JSONObject doInBackground(String... args){
JSONParser jsonParser = new JSONParser();
Log.i("URL", url);
JSONObject json = jsonParser.getJSONFromUrl(url);
if(json == null) {
Log.i("Json obj =" , "NULL");
}
else{
return json;
}
return new JSONObject();
}
#Override
protected void onPostExecute(JSONObject json){
progressDialog.dismiss();
//String shopName ="";
// String distance="";
try{
//Fetching JSON Array
Log.i("JSON", json.toString());
jsonData = new JSONArray(json);
Double arrivalTime= 0.0;
for(int i=0;i<json.length();i++) {
try {
JSONObject c = json.getJSONObject(i);
busNoArray.add(json.getString(TAG_LINEID));
destinationArray.add(json.getString(TAG_DESTINATION));
arrivalTime = json.getDouble(TAG_TIME) / 60;
arrivalTimeArray.add(arrivalTime);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter = new BusTimeAdapter(BusTimeActivity.this,busNoArray, destinationArray, arrivalTimeArray);
mListView.setAdapter(adapter);`
Can someone help me pls?
First be sure you have retrieved JSON String,
Then You can easily access the properties inside them like
try {
JSONArray jsonArray = new JSONArray(json);
JSONObject obj = jsonArray.getJSONObject(0); //0 for just retrieving first object you can loop it
String myVehicleID = obj.getString("vehicleId"); //To retrieve vehicleId
//Similarly do it for others as well
} catch (JSONException e) {
e.printStackTrace();
}
Related
{
"status": "1",
"message": "",
"result": {
"info": {
"tax": "0",
"discount": "0",
"minimum_spend": "300",
"delivery_charges": "0",
"last_updated": "1 week 15 hours ago"
},
"items": [
{
"name": "Eat At Home",
"menu_item_id": "12345",
"menu_cat_id": "4321",
"menu_cat_sku": "",
"nutritions": "",
"price": "1000",
"currency": "USD",
"desc": "Desription",
"category": "Promotion",
"image": "https://static.google.com/media/images/thumbs/343e8f41b18325a6058adc3773ed4d53.png",
"large_image": "https://static.google.com/media/images/343e8f41b18325a6058adc3773ed4d53.png",
"options": [],
"discount": "",
"weight": "",
"sku": "",
"status": "0",
"brand": []
},
{
"name": "Lunch Bundle",
"menu_item_id": "4321",
"menu_cat_id": "4321",
"menu_cat_sku": "",
"nutritions": "",
"price": "1500",
"currency": "USD",
"desc": "Description",
"category": "Promotion",
"image": "https://static.google.com/media/images/thumbs/62cdde279bbc3e45b8456f040d649b32.png",
"large_image": "https://static.google.com/media/images/62cdde279bbc3e45b8456f040d649b32.png",
"options": [],
"discount": "",
"weight": "",
"sku": "",
"status": "0",
"brand": []
},
My code
MenuResponse menuResponse = JsonParser.getInstance().parseMenuResponse(response);
public MenuResponse parseMenuResponse(String serverResponse) throws Exception {
MenuResponse response = null;
if (serverResponse != null) {
try {
response = gson.fromJson(serverResponse, MenuResponse.class);
} catch (JsonSyntaxException jse) {
throw new Exception(ERROR_MESSAGE);
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
try this.
JSONObject json = new JSONObject(response);
String status= json.getString("status");
JSONArray itemsArray= json.getJSONArray("items");
for (int i = 0; i < itemsArray.length(); i++) {
JSONObject c = itemsArray.getJSONObject(i);
String name= c.getString("name");
//remaining data you will
}
Or else better you can use Retrofit.
I am trying to parse a JSON String and map it to a hashmap, I have a valid JSONString from server but when I traverse through it, all I can get it is the first result.
JSONArray peoples = null;
ArrayList<HashMap<String, String>> personList = new ArrayList<HashMap<String,String>>();
JSONObject jsonObj = new JSONObject(value);
Log.d("Jello",jsonObj.toString());
peoples = jsonObj.getJSONArray("product");//check here
Log.d("Jello",peoples.toString());
for(int i=0;i<peoples.length();i++){
JSONObject c = peoples.getJSONObject(i);
String service_group = c.getString("sgroup");
String service = c.getString("service");
String value = c.getString("value");
String updated_at = c.getString("updated_at");
HashMap<String,String> persons = new HashMap<String,String>();
persons.put("service_group",service_group);
persons.put("service",service);
persons.put("value",value);
persons.put("updated_at",updated_at);
personList.add(persons);
}
My JSON String is :
{"product":[{"sgroup":"Dummy_BIG_ONE","service":"Dummy_UNDER_BIG_ONE","code":"128","value":"0","updated_at":"2015-12-04 21:21:00"}]}{"product":[{"sgroup":"Hello Monkey","service":"Do u work","code":"123","value":"0","updated_at":"2015-12-04 21:27:51"}]}{"product":[{"sgroup":"Checking from Android Device","service":"Monkey","code":"12345","value":"0","updated_at":"2015-12-04 22:55:39"}]}{"product":[{"sgroup":"Checking from Android Device","service":"Monkey","code":"12345","value":"0","updated_at":"2015-12-04 22:55:40"}]}{"product":[{"sgroup":"Checking from Android Device","service":"Monkey","code":"12345","value":"0","updated_at":"2015-12-04 22:55:42"}]}{"product":[{"sgroup":"Hello World","service":"Donkey","code":"24411","value":"0","updated_at":"2015-12-04 22:57:05"}]}{"product":[{"sgroup":"lkfnhjdiofho","service":"dfjdifj","code":"1101","value":"0","updated_at":"2015-12-05 01:15:49"}]}{"product":[{"sgroup":"Baal","service":"Saal","code":"1234","value":"21","updated_at":"2015-12-05 01:34:59"}]}{"product":[{"sgroup":"Inis","service":"Mona","code":"1234","value":"1001","updated_at":"2015-12-05 01:39:51"}]}{"product":[{"sgroup":"Medical Treatment Loan","service":"Number of referral slip","code":"128","value":"0","updated_at":"2015-12-05 01:50:42"}]}{"product":[{"sgroup":"Medical Treatment Loan","service":"Number of referral slip","code":"128","value":"0","updated_at":"2015-12-05 01:55:12"}]}{"product":[{"sgroup":"Medical Treatment Loan","service":"Number of referral slip","code":"128","value":"1000","updated_at":"2015-12-05 01:56:10"}]}
or HERE
here is how I am sending the JSON
while($row = mysql_fetch_assoc($output))
{
$product = array();
$product["sgroup"] = $row["service_group"];
$product["service"] = $row["service"];
$product["code"] = $row["code"];
$product["value"] = $row["amount"];
$product["updated_at"] = $row["updated_at"];
// user node
$response["product"] = array();
array_push($response["product"], $product);
// echoing JSON response
echo json_encode($response);
}
I want to add all the data's from the JSON in my ArrayList so that I can use it later.
Thank you for your help.
First, there are online tools available to determine if your JSON is valid.
Here is a general example of a better way to format your JSON data:
<?php
$bigArray = array();
for ($x = 0; $x <= 10; $x++) {
$product = array();
$product["sgroup"] = $x;
$product["service"] = $x;
$product["code"] = $x;
$product["value"] = $x;
$product["updated_at"] = $x;
array_push($bigArray, $product);
}
// echoing JSON response
echo json_encode($bigArray);
?>
Which gives this valid JSON response that is simple and easy to parse:
[
{
"sgroup":0,
"service":0,
"code":0,
"value":0,
"updated_at":0
},
{
"sgroup":1,
"service":1,
"code":1,
"value":1,
"updated_at":1
},
{
"sgroup":2,
"service":2,
"code":2,
"value":2,
"updated_at":2
},
{
"sgroup":3,
"service":3,
"code":3,
"value":3,
"updated_at":3
},
{
"sgroup":4,
"service":4,
"code":4,
"value":4,
"updated_at":4
},
{
"sgroup":5,
"service":5,
"code":5,
"value":5,
"updated_at":5
},
{
"sgroup":6,
"service":6,
"code":6,
"value":6,
"updated_at":6
},
{
"sgroup":7,
"service":7,
"code":7,
"value":7,
"updated_at":7
},
{
"sgroup":8,
"service":8,
"code":8,
"value":8,
"updated_at":8
},
{
"sgroup":9,
"service":9,
"code":9,
"value":9,
"updated_at":9
},
{
"sgroup":10,
"service":10,
"code":10,
"value":10,
"updated_at":10
}
]
As for the parsing, using a HashMap is not the best way. Create a list of Person POJO objects.
First define the Person class:
class Person {
public String group;
public String service;
public String value;
public String updated;
public Person(String g, String s, String v, String u) {
group = g;
service = s;
value = v;
updated = u;
}
}
Then, parsing is fairly simple:
List<Person> personList = new ArrayList<>();
JSONArray jsonArr;
try {
jsonArr = new JSONArray(response);
for(int i=0;i<jsonArr.length();i++){
JSONObject c = jsonArr.getJSONObject(i);
String service_group = c.getString("sgroup");
String service = c.getString("service");
String value = c.getString("value");
String updated_at = c.getString("updated_at");
Person p = new Person(service_group, service, value, updated_at);
personList.add(p);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
You should put your products into json array:
[
{
"product": {
"sgroup": "lkfnhjdiofho",
"service": "dfjdifj",
"code": "1101",
"value": "0",
"updated_at": "2015-12-05 01:15:49"
}
},
{
"product": {
"sgroup": "Baal",
"service": "Saal",
"code": "1234",
"value": "21",
"updated_at": "2015-12-05 01:34:59"
}
},
{
"product": {
"sgroup": "Inis",
"service": "Mona",
"code": "1234",
"value": "1001",
"updated_at": "2015-12-05 01:39:51"
}
},
{
"product": {
"sgroup": "Medical Treatment Loan",
"service": "Number of referral slip",
"code": "128",
"value": "0",
"updated_at": "2015-12-05 01:50:42"
}
},
{
"product": {
"sgroup": "Medical Treatment Loan",
"service": "Number of referral slip",
"code": "128",
"value": "0",
"updated_at": "2015-12-05 01:55:12"
}
},
{
"product": {
"sgroup": "Medical Treatment Loan",
"service": "Number of referral slip",
"code": "128",
"value": "1000",
"updated_at": "2015-12-05 01:56:10"
}
}
]
And you have to change your parser little bit:
JSONArray jsonArray = new JSONArray(string);
for(int i=0;i<jsonArray.length();i++){
JSONObject c = jsonArray.getJSONObject(i).getJSONObject("product");
String service_group = c.getString("sgroup");
String service = c.getString("service");
String value = c.getString("value");
String updated_at = c.getString("updated_at");
HashMap<String,String> persons = new HashMap<String,String>();
persons.put("service_group",service_group);
persons.put("service",service);
persons.put("value",value);
persons.put("updated_at",updated_at);
personList.add(persons);
}
You don't need put your object into "product" attribute, but directly into array :
[
{
"sgroup": "lkfnhjdiofho",
"service": "dfjdifj",
"code": "1101",
"value": "0",
"updated_at": "2015-12-05 01:15:49"
},
{
"sgroup": "Baal",
"service": "Saal",
"code": "1234",
"value": "21",
"updated_at": "2015-12-05 01:34:59"
},
I want to create a JSON Object using String.
Example :
JSON {"test1":"value1","test2":{"id":0,"name":"testName"}}
In order to create the above JSON I am using this.
String message;
JSONObject json = new JSONObject();
json.put("test1", "value1");
JSONObject jsonObj = new JSONObject();
jsonObj.put("id", 0);
jsonObj.put("name", "testName");
json.put("test2", jsonObj);
message = json.toString();
System.out.println(message);
I want to know how can I create a JSON which has JSON Array in it.
Below is the sample JSON.
{
"name": "student",
"stu": {
"id": 0,
"batch": "batch#"
},
"course": [
{
"information": "test",
"id": "3",
"name": "course1"
}
],
"studentAddress": [
{
"additionalinfo": "test info",
"Address": [
{
"H.No": "1243",
"Name": "Temp Address",
"locality": "Temp locality",
"id":33
},
{
"H.No": "1243",
"Name": "Temp Address",
"locality": "Temp locality",
"id":33
},
{
"H.No": "1243",
"Name": "Temp Address",
"locality": "Temp locality",
"id":36
}
],
"verified": true,
}
]
}
Thanks.
org.json.JSONArray may be what you want.
String message;
JSONObject json = new JSONObject();
json.put("name", "student");
JSONArray array = new JSONArray();
JSONObject item = new JSONObject();
item.put("information", "test");
item.put("id", 3);
item.put("name", "course1");
array.put(item);
json.put("course", array);
message = json.toString();
// message
// {"course":[{"id":3,"information":"test","name":"course1"}],"name":"student"}
In contrast to what the accepted answer proposes, the documentation says that for JSONArray() you must use put(value) no add(value).
https://developer.android.com/reference/org/json/JSONArray.html#put(java.lang.Object)
(Android API 19-27. Kotlin 1.2.50)
If you use the gson.JsonObject you can have something like that:
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
String jsonString = "{'test1':'value1','test2':{'id':0,'name':'testName'}}"
JsonObject jsonObject = (JsonObject) jsonParser.parse(jsonString)
String jsonString = "{'element1':'value1','element2':{'id':0,'name':'testName'}}";
JsonObject jsonObject = (JsonObject) JsonParser.parseString(jsonString);
Underscore-java can create json from an object.
import com.github.underscore.U;
String message = U.objectBuilder()
.add("course", U.arrayBuilder()
.add(U.objectBuilder()
.add("id", 3)
.add("information", "test")
.add("name", "course1")
))
.add("name", "student")
.toJson();
System.out.println(message);
// {
// "course": [
// {
// "id": 3,
// "information": "test",
// "name": "course1"
// }
// ],
// "name": "student"
// }
I have this JSON result page, i want to parse it in .java
[
{
"kind": "track",
"id": 12429087,
"created_at": "2011/03/23 19:10:55 +0000",
"user_id": 2297976,
"duration": 473257,
"commentable": true,
"state": "finished",
"original_content_size": 19029935,
"sharing": "public",
"tag_list": "",
"permalink": "adikta-llega-la-calma-en-vivo",
"streamable": true,
"embeddable_by": "all",
"downloadable": true,
"purchase_url": null,
"label_id": null,
"purchase_title": null,
"genre": "",
"title": "ADIKTA - LLEGA LA CALMA en vivo 6",
"description": "",
"label_name": "",
"release": "",
"track_type": "",
"key_signature": "",
"isrc": "",
"video_url": null,
"bpm": null,
"release_year": null,
"release_month": null,
"release_day": null,
"original_format": "mp3",
"license": "all-rights-reserved",
"uri": "http://api.soundcloud.com/tracks/12429087",
"user": {
"id": 2297976,
"kind": "user",
"permalink": "adikta",
"username": "adikta",
"uri": "http://api.soundcloud.com/users/2297976",
"permalink_url": "http://soundcloud.com/adikta",
"avatar_url": "http://i1.sndcdn.com/avatars-000002155791-15emwj-large.jpg?3eddc42"
},
"permalink_url": "http://soundcloud.com/adikta/adikta-llega-la-calma-en-vivo",
"artwork_url": "http://i1.sndcdn.com/artworks-000005792200-72zfn4-large.jpg?3eddc42",
"waveform_url": "http://w1.sndcdn.com/hPYrb5G8V4an_m.png",
"stream_url": "http://api.soundcloud.com/tracks/12429087/stream",
"download_url": "http://api.soundcloud.com/tracks/12429087/download",
"playback_count": 114,
"download_count": 19,
"favoritings_count": 1,
"comment_count": 0,
"attachments_uri": "http://api.soundcloud.com/tracks/12429087/attachments"
},
this is my .java class (android) code:
try {
JSONObject respObj = new JSONObject(result);
JSONObject topTracksObj = respObj.getJSONObject("tracks");
JSONArray tracks = topTracksObj.getJSONArray("track");
for(int i=0; i<tracks.length(); i++) {
JSONObject track = tracks.getJSONObject(i);
String trackName = track.getString("permalink");
String trackUrl = track.getString("permalink_url");
JSONObject artistObj = track.getJSONObject("user");
String artistName = artistObj.getString("permalink");
String artistUrl = artistObj.getString("uri");
String imageUrl;....
But i cant find any solution to parse or navigate in this JSON directory without ids.
the api im using is soundcloud, but i cant find the answer there either. any help would be appreciated.
any suggestion?
thanks in advance
Kindly find the below mentioned code:
String str = "<YOUR_JSON_STRING>";
JSONArray jArrayObject;
try {
jArrayObject = new JSONArray(str);
for (int i = 0; i<jArrayObject.length(); i++) {
Log.d("kind==", jArrayObject.getJSONObject(i).getString("kind").toString());
Log.d("id==", jArrayObject.getJSONObject(i).getString("id").toString());
Log.d("created_at==", jArrayObject.getJSONObject(i).getString("created_at").toString());
JSONObject jObj = new JSONObject(jArrayObject.getJSONObject(i).getString("user").toString());
Log.d("id==", jObj.getString("id").toString());
Log.d("kind==", jObj.getString("kind").toString());
Log.d("permalink==", jObj.getString("permalink").toString());
Log.d("username==", jObj.getString("username").toString());
Log.d("permalink_url==", jObj.getString("permalink_url").toString());
Log.d("avatar_url==", jObj.getString("avatar_url").toString());
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
How can I parse this piece of JSON code?
{
"direction": "ltr",
"id": "feed/http => //www.theverge.com/rss/full.xml",
"title": "The Verge - All Posts",
"continuation": "CLKM0OyU0rYC",
"self": [
{
" href": "https => //cloud.feedly.com/reader/3/stream/contents/feed%2Fhttp%3A%2F%2Fwww.theverge.com%2Frss%2Ffull.xml?n=20&unreadOnly=true"
}
],
"alternate": [
{
"href": "http://www.theverge.com/",
"type": "text/html"
}
],
"updated": 1367539068016,
"items": [
{
"id": "entryId",
"unread": true,
"categories": [
{
"id": "user/c805fcbf-3acf-4302-a97e-d82f9d7c897f/category/tech",
"label": "tech"
}
],
"tags": [
{
"id": "user/c805fcbf-3acf-4302-a97e-d82f9d7c897f/tag/inspiration",
"label": "inspiration"
}
],
"title": "NBC's reviled sci-fi drama 'Heroes' may get a second lease on life as Xbox Live exclusive",
"published": 1367539068016,
"updated": 1367539068016,
"crawled": 1367539068016,
"alternate": [
{
"href": "http://www.theverge.com/2013/4/17/4236096/nbc-heroes-may-get-a-second-lease-on-life-on-xbox-live",
"type": "text/html"
}
],
"content": {
"direction": "ltr",
"content": "..."
},
"author": "Nathan Ingraham",
"origin": {
"streamId": "feed/http://www.theverge.com/rss/full.xml",
"title": "The Verge - All Posts",
"htmlUrl": "http://www.theverge.com/"
},
"engagement": 15
},
{
"id": "entryId2",
"unread": true,
"categories": [
{
"id": "user/c805fcbf-3acf-4302-a97e-d82f9d7c897f/category/tech",
"label": "tech"
}
],
"tags": [
{
"id": "user/c805fcbf-3acf-4302-a97e-d82f9d7c897f/tag/inspiration",
"label": "inspiration"
}
],
"title": "Senate rejects bipartisan gun control measure for background checks despite broad public support",
"published": 1367539068016,
"updated": 1367539068016,
"crawled": 1367539068016,
"alternate": [
{
"href": "http://www.theverge.com/2013/4/17/4236136/senate-rejects-gun-control-amendment",
"type": "text/html"
}
],
"content": {
"direction": "ltr",
"content": "...html content..."
},
"author": "T.C. Sottek",
"origin": {
"streamId": "feed/http://www.theverge.com/rss/full.xml",
"title": "The Verge - All Posts",
"htmlUrl": "http://www.theverge.com/"
},
"engagement": 39
}
]
}
That is my solution but it doesn't work... what is my error? thanks
try{
//JSONArray elements = new JSONArray (response);
JSONObject json=new JSONObject(response);
JSONArray elements = json.getJSONArray("items");
Log.d(TAG, "Elemenenti numero" +elements.length());
// Getting Array of Contacts
// looping through All Contacts
for(int i = 0; i < elements.length(); i++){
JSONObject c = elements.getJSONObject(i);
// Storing each json item in variable
String identifier = c.getString("id");
String title = c.getString("title");
String link = c.getString("originId");
String data = c.getString("published");
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
Date date=new Date();
try {
date = format.parse(data);
System.out.println(date);
} catch (Exception e) {
e.printStackTrace();
}
JSONObject summaryObj= c.getJSONObject("summary");
String summary = summaryObj.getString("content");
JSONObject contentObj= c.getJSONObject("content");
String content = contentObj.getString("content");
JSONObject sourceObj= c.getJSONObject("origin");
String source = contentObj.getString("title");
if (summary.length()==0 && content.length()!=0) summary=content;
if (content.length()==0 && summary.length()!=0) content=summary;
String image=this.getFirstImage(content);
FeedItem toAdd=new FeedItem(identifier, title, link, date, null, summary, content, image, source);
toAdd.toString();
}
}catch (JSONException e) {
e.printStackTrace();
}
JSONObject summaryObj= c.getJSONObject("summary");
There is no element called summary, you may try
if(c.has("summary")) {
JSONObject summaryObj= c.getJSONObject("summary");
}
if that doesn't work, please post your stacktrace, (logcat)
You don't have any tag named "originID". but you are trying to get String from it.
Similarly,you don't have tag "summary" also but you are trying to get JSONObject from it.