I have to parse the Json below. I know how to obtain Json from a JsonArray when it has a key. How do I do this when I don't have any key?
[
{
"kind": "track",
"id": 253792869,
"created_at": "2016/03/21 15:20:47 +0000",
"user_id": 167064157,
"duration": 9457,
"commentable": true,
"state": "finished",
"original_content_size": 375488,
"last_modified": "2016/03/21 15:20:48 +0000",
"sharing": "public",
"tag_list": "commercial",
"permalink": "2016-03-08_lbs_bigfm_spot_3",
"streamable": true,
"embeddable_by": "all",
"downloadable": false,
"purchase_url": null,
"label_id": null,
"purchase_title": null,
"genre": "",
"title": "2016-03-08_LBS_BigFM_SPOT_3",
"description": "",
"label_name": null,
"release": null,
"track_type": null,
"key_signature": null,
"isrc": null,
"video_url": null,
"bpm": null,
"release_year": null,
"release_month": null,
"release_day": null,
"original_format": "mp3",
"license": "all-rights-reserved",
"uri": "https://api.soundcloud.com/tracks/253792869",
"user": {
"id": 167064157,
"kind": "user",
"permalink": "user690075536",
"username": "user690075536",
"last_modified": "2016/02/26 08:19:23 +0000",
"uri": "https://api.soundcloud.com/users/167064157",
"permalink_url": "http://soundcloud.com/user690075536",
"avatar_url": "https://i1.sndcdn.com/avatars-000159639971-j1awdb-large.jpg"
},
"permalink_url": "http://soundcloud.com/user690075536/2016-03-08_lbs_bigfm_spot_3",
"artwork_url": "https://i1.sndcdn.com/artworks-000152760877-s9mcat-large.jpg",
"waveform_url": "https://w1.sndcdn.com/8Ijd5YlUn9iW_m.png",
"stream_url": "https://api.soundcloud.com/tracks/253792869/stream",
"playback_count": 0,
"download_count": 0,
"favoritings_count": 0,
"comment_count": 0,
"attachments_uri": "https://api.soundcloud.com/tracks/253792869/attachments"
}
]
Valid JSON:
{
"abc":[
{
"name":"Ram"
},
{
"name":"Shyam"
},
{
"name":"Mohan"
},
{
"name":"Pankaj"
},
{
"name":"Komal"
}
]
}
try
{
JSONArray jsonArray = new JSONArray(jsonStrFromSoundCloud);
for (int i = 0; i < jsonArray.length(); i++) {
//loop in array
}
} catch (JSONException e) {
e.printStackTrace();
}
I got my answer, I bind this array inside a json object. then fetch it.
similar like this.
"{\"data\":"+ jsonArray+"}";
I tried to solve similar issue by creating a json array.
[{ "name":"dave",
"age":23
},
{
"name" : "dexter"
"age" : 24
}]
Here is my POJO
public class MyPojo {
private String name;
private int age;
// Getter & Setters
}
And this is all you need to do to parse the JSON to List object.
Type listType = new TypeToken<ArrayList<MyPojo>>(){}.getType();
List<MyPojo> jsonObject = new Gson().fromJson(response, listType);
Hope this helps. :)
EDIT
Don't forget to Import : import java.lang.reflect.Type;
Related
This question already has answers here:
How do I parse JSON in Android? [duplicate]
(3 answers)
Closed 5 years ago.
I am developing a map application on Android which is about finding best roads.
The problem is not all roads name are on Google API so i have it on one JSon file.
Which is the best way to get coordinates from JSon file and show it to Android App
with lines from position A to B.
{
"type": "FeatureCollection",
"crs": {
"type": "name",
"properties": {
"name": "urn:ogc:def:crs:OGC:1.3:CRS84"
}
},
"features": [
{
"type": "Feature",
"properties": {
"Name": "po",
"description": "",
"timestamp": null,
"begin": null,
"end": null,
"altitudeMode": null,
"tessellate": -1,
"extrude": 0,
"visibility": -1,
"drawOrder": null,
"icon": null,
"description_1": null,
"Number": "10",
"RoadNameCo": "03_10234",
"RoadNameAL": "MEHDI HOXHA"
},
"geometry": {
"type": "Point",
"coordinates": [
20.853835,
42.601668,
0
]
}
},
{
"type": "Feature",
"properties": {
"Name": "po",
"description": "",
"timestamp": null,
"begin": null,
"end": null,
"altitudeMode": null,
"tessellate": -1,
"extrude": 0,
"visibility": -1,
"drawOrder": null,
"icon": null,
"description_1": null,
"Number": "16",
"RoadNameCo": "03_10234",
"RoadNameAL": "MEHDI HOXHA"
},
"geometry": {
"type": "Point",
"coordinates": [
20.854006,
42.60127,
0
]
}
}
]
}
Try this
private List<LatLng> getLocationList(String JSON_String)
{
List<LatLng> locationList = new ArrayList<>();
try {
JSONObject object = new JSONObject(JSON_String);
JSONArray mArray = object.getJSONArray("features");
for(int i=0;i<mArray.length();i++){
JSONObject obj=mArray.getJSONObject(i);
JSONObject geometryObject=obj.getJSONObject("geometry");
JSONArray locationJSON_Array=geometryObject.getJSONArray("coordinates");
LatLng location=new LatLng(locationJSON_Array.getDouble(0),locationJSON_Array.getDouble(1));
locationList.add(location);
}
}catch (JSONException ex){
ex.printStackTrace();
//handle Exception
}
return locationList;
}
Use it like this
List<LatLng> LocationList =getLocationList(Your_JSON_String);//The String posted in question
LatLng firstLocation=locationList.get(0);
LatLng secondLocation=locationList.get(1);
Let me Know if anything goes wrong
Just try to parse like this:
JSONArray lat_long_jsonArray = jsonObject.getJSONArray("coordinates");
if (lat_long_jsonArray.length() != 0)
{
String Longitude(lat_long_jsonArray.get(0).toString());
String Latitude(lat_long_jsonArray.get(1).toString());
}
I want to fetch array from json object but get error
When I do jarray2 = object1.getJSONArray(route);
I get the following error
APPÂ CRASH: No value for (the following JSON)
[{
"options": {
"allowUTurn": false
},
"latLng": {
"lat": 52.42252295423907,
"lng": 4.873809814453125
},
"name": "Coenplein, A10, Amsterdam, Noord, Amsterdam, MRA, Stadsregio Amsterdam, North Holland, Netherlands, 1035RN, The Netherlands",
"_initHooksCalled": true
}, {
"options": {
"allowUTurn": false
},
"latLng": {
"lat": 52.28674750920209,
"lng": 4.941873550415039
},
"name": "Holendrechterzijweg, Ouderkerk aan de Amstel, Ouder-Amstel, MRA, Stadsregio Amsterdam, North Holland, Netherlands, 1191LJ, The Netherlands",
"_initHooksCalled": true
}, {
"options": {
"allowUTurn": false
},
"latLng": {
"lat": 52.0727536539532,
"lng": 4.32861328125
},
"name": "87, Zwetstraat, Rivierenbuurt, The Hague, MRDH, South Holland, Netherlands, 2515VE, The Netherlands",
"_initHooksCalled": true
}]
Here is the code
try
{
object1 = new JSONObject(response);
jarray1 = object1.getJSONArray("selected_route_data");
for(int i=0;i<jarray1.length();i++)
{
json1 = jarray1.getJSONObject(i);
String route_id = json1.getString("route_id").toString();
String route_name = json1.getString("route_name").toString();
String route = json1.getString("route_data").toString();
jarray2 = object1.getJSONArray(route);
}
}
catch (JSONException e)
{
Log.e("APP CRASH", e.getMessage());
}
It appears the JSON you are attempting to parse does not contain the values you are looking for. None of the elements in the array contain either route_id, route_name or route_data.
You should check if an element exists in the JSON you are parsing, you can do something like
String route_id = null;
if (!json1.optString("route_id").isEmpty()) {
route_id = json1.getString("route_id").toString();
}
I have a json string as shown below
{
"college": {
"id": "RPD4007",
"address": "#302, 1 st cross"
},
"deparment": {
"department1": {
"name": {
"maths": {
"chapter": 1,
"name": "algebra",
"module_id": "01"
},
"electronics": {
"chapter": 1,
"name": "ec",
"module_id": "01"
}
}
},
"department2": {
"name": {
"english": {
"chapter": 2,
"name": "algebra",
"module_id": "02"
},
"electrical": {
"chapter": 2,
"name": "algebra",
"module_id": "02"
}
}
}
}
}
I have tried to convert this json sring to json object ,
string json_string = EntityUtils.toString(response.getEntity());
jObj = new JSONObject(json_string);//json object
JSONObject object = jobj.getJSONObject("college");
But the jobj output I got is in reverse order of json string .Like below,
{
"college": {
"id": "RPD4007",
"address": "#302, 1 st cross"
},
"deparment": {
"department2": {
"name": {
"electrical": {
"chapter": 2,
"name": "algebra",
"module_id": "02"
},
"english": {
"chapter": 2,
"name": "algebra",
"module_id": "02"
}
}
},
"department1": {
"name": {
"electronics": {
"chapter": 1,
"name": "ec",
"module_id": "01"
},
"maths": {
"chapter": 1,
"name": "algebra",
"module_id": "01"
}
}
}
}
}
How to get it in same order as it is?
I think you are making jsonObject for two times.
Just do something like this
you have String that contains JSON DATA
Make an object for that which you did
string json_string = EntityUtils.toString(response.getEntity());
jObj = new JSONObject(json_string);//json object
then make a loop to get the object inside that object using
String college = jobj.getString("college");
The answers here: JSON order mixed up
As a consequence, JSON libraries are free to rearrange the order of the elements as they see fit. This is not a bug.
I am trying to access value of 'cod' from the json string :
{"coord":{"lon":73.86,"lat":18.52},"sys":{"message":0.0293,"country":"IN","sunrise":1428972502,"sunset":1429017681},"weather":[{"id":801,"main":"Clouds","description":"few clouds","icon":"02d"}],"base":"stations","main":{"temp":304.301,"temp_min":304.301,"temp_max":304.301,"pressure":951.61,"sea_level":1021.56,"grnd_level":951.61,"humidity":36},"wind":{"speed":2.06,"deg":302.501},
"clouds":{"all":24},"dt":1428996633,"id":1259229,"name":"Pune","cod":200}
But I am not able to get this value from my code. the code I am using to access this value from json string is as:
try{
JSONObject jsObject=(new JSONObject(JsonString)).getJSONObject("coord");
if( jsObject.getInt("cod")==200) {
i.putExtra("jsn", JsonString);
i.putExtra("city", etCity.getText().toString());
startActivity(i);
}
In the if condition, you are trying to access the key "cod" in the array {"lon":73.86,"lat":18.52}. It will throw a JSONException.
Try this :
try{
JSONObject jsonmain = new JSONOBject(JsonString);
if(jsonmain.getInt("cod") == 200) {
i.putExtra("jsn", JsonString);
i.putExtra("city", etCity.getText().toString());
startActivity(i);
}
Your json is:
{
"coord": {
"lon": 73.86,
"lat": 18.52
},
"sys": {
"message": 0.0293,
"country": "IN",
"sunrise": 1428972502,
"sunset": 1429017681
},
"weather": [
{
"id": 801,
"main": "Clouds",
"description": "few clouds",
"icon": "02d"
}
],
"base": "stations",
"main": {
"temp": 304.301,
"temp_min": 304.301,
"temp_max": 304.301,
"pressure": 951.61,
"sea_level": 1021.56,
"grnd_level": 951.61,
"humidity": 36
},
"wind": {
"speed": 2.06,
"deg": 302.501
},
"clouds": {
"all": 24
},
"dt": 1428996633,
"id": 1259229,
"name": "Pune",
"cod": 200
}
The key "cod" is not nested inside "coord".
Try:
new JSONObject(JsonString)).getInt("cod");
Actually you are trying wrong JSON Object.
String cod=(new JSONObject(JsonString)).getJSONObject("code").toString();
//you may need to try catch block
if( Integer.parseint(cod)==200) {
.... Your logic
}
I am getting the response
{
"returnCode": "0",
"message": "Sucessfully get credit card for value(1) ",
"token": "",
"CreditCard": {
"class": "CreditCard",
"id": 1,
"bankName": "NA",
"cardNumber": "1233435467789",
"ccvNumber": "3455",
"dateCreated": "2012-02-10T10:20:06Z",
"expiryDate": "2012-02-29T18:30:00Z",
"expiryDateStr": null,
"lastUpdated": "2012-02-10T10:20:06Z",
"securityCode": null,
"type": {
"enumType": "CreditCardType",
"name": "Visa"
},
"user": {
"class": "User",
"id": 4
}
}
}
I can't change server code, so how do i parse it. any helped..
your enum:
enum CreditCardType{
Visa, MasterCard, Diners
}
and while parsing, when you reach till type
//param is JSONObject
CreditCardType card = CreditCardType.valueOf(param.getString("name"));