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();
}
Related
I want to convert this web service string to JSONArray , but it seems to have a problem , although I've validated it.
[
{
"hireDate": null,
"homePhoneNumber": null,
"gender": null,
"city": null,
"mobileNumber": null,
"idNumber": 123,
"religion": null,
"leftOver": 1,
"annualVacations": 5,
"dob": null,
"name": null,
"rank": 0,
"id": 1,
"workingHours": [],
"email": "ayman.daraghmah#exalt.ps",
"managers": [],
"alternativeMobileNumber": null,
"activated": true,
"username": "ayman.daraghmah#exalt.ps"
},
{
"hireDate": null,
"homePhoneNumber": null,
"gender": null,
"city": null,
"mobileNumber": null,
"idNumber": 123,
"religion": null,
"leftOver": 1,
"annualVacations": 5,
"dob": null,
"name": null,
"rank": 0,
"id": 11,
"workingHours": [],
"email": "aymandaraghmah#gmail.com",
"managers": [],
"alternativeMobileNumber": null,
"activated": true,
"username": "aymandaraghmah#gmail.com"
}
]
My Code:
JSONArray js = new JSONArray(payload);
what should the format of payload be to create the JSONArray ?
Looking at the code it looks like it should work. Following sample worked for me (The JSON is taken as a string for testing).
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Main {
public static void main(String[] args) throws JSONException {
String test = "[{\"hireDate\": null,\"homePhoneNumber\": null,\"gender\": null,\"city\": null,\"mobileNumber\": null,\"idNumber\": 123,\"religion\": null,\"leftOver\": 1,\"annualVacations\": 5,\"dob\": null,\"name\": null,\"rank\": 0,\"id\": 1,\"workingHours\": [],\"email\": \"ayman.daraghmah#exalt.ps\",\"managers\": [],\"alternativeMobileNumber\": null,\"activated\": true,\"username\": \"ayman.daraghmah#exalt.ps\"},{\"hireDate\": null,\"homePhoneNumber\": null,\"gender\": null,\"city\": null,\"mobileNumber\": null,\"idNumber\": 123,\"religion\": null,\"leftOver\": 1,\"annualVacations\": 5,\"dob\": null,\"name\": null,\"rank\": 0,\"id\": 11,\"workingHours\": [],\"email\": \"aymandaraghmah#gmail.com\",\"managers\": [],\"alternativeMobileNumber\": null,\"activated\": true,\"username\": \"aymandaraghmah#gmail.com\"}]";
JSONArray jsonArray = new JSONArray(test);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject explrObject = jsonArray.getJSONObject(i);
System.out.println(explrObject.getString("username"));
}
}
}
I would recommend you to follow this link to get your problem solve.
http://www.java67.com/2016/10/3-ways-to-convert-string-to-json-object-in-java.html
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();
}
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 parse this json in android. Can you help me how to parse, if i need to start from head to parse or from results for this I don't know. Can you help me
{
"head":
{
"link": [],
"vars": ["city", "country"]
},
"results":
{
"distinct": false,
"ordered": true,
"bindings":
[
{
"city":
{
"type": "uri",
"value": "http://dbpedia.org/resource/Ferizaj"
} ,
"country":
{
"type": "uri",
"value": "http://dbpedia.org/resource/Kosovo"
}
}
]
}
}
Okay, first of all the JSON string you've given is invalid. I've written my answer based on the correct version of the JSON string that you have provided
{
"head":
{
"link": [],
"vars": ["city", "country"]
},
"results":
{
"distinct": false,
"ordered": true,
"bindings":
[
{
"city":
{
"type": "uri",
"value": "http://dbpedia.org/resource/Ferizaj"
} ,
"country":
{
"type": "uri",
"value": "http://dbpedia.org/resource/Kosovo"
}
}
]
}
}
Now, to get the "values", you'll need to do this.
JSONObject jsonObject = new JSONObject(response);
JSONObject results = jsonObject.getJSONObject("results");
JSONArray bindings = results.getJSONArray("bindings");
for (int i = 0; i < bindings.length(); i++) {
JSONObject binding = bindings.getJSONObject(i);
JSONObject city = binding.getJSONObject("city");
// Get value in city
String cityValue = city.getString("value");
Log.d("CITY", cityValue);
JSONObject country = binding.getJSONObject("country");
// Get value in country
String countryValue = country.getString("value");
Log.d("COUNTRY", countryValue);
}
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.