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.
Related
I got below JSONObject from Firebase.
There is no any JSONArray in response.
How can I get all main JSONObject with loop.?
Is below JSON response is valid? or I have to convert into JSONArray ?
I know how to get inner JSONObject if there is JSONArray.
{
"Data": {
"inner_data": {
"key1": {
"chapter": "Chapter 1",
"key": "key",
"weight": 1
},
"key2": {
"chapter": "Chapter 2",
"key": "-KMa5xai7vMQtaDZ0b31",
"weight": 2
}
}
},
"Demo": {
"inner_demo": {
"key1": {
"chapter": "Chapter 1",
"key": "key",
"weight": 1
},
"key2": {
"chapter": "Chapter 2",
"key": "-KMa5xai7vMQtaDZ0b31",
"weight": 2
}
}
},
"Test": {
"inner_test1": {
"-KMa9JFjKuDNgf313Bzc": {
"key": "-KMa9JFjKuDNgf313Bzc",
"time": "10:33",
"topic": "Circles",
"url": "https://www.youtube.com/watch?v=yLVsv9kO5C8",
"weight": 1
}
},
"-inner_test2": {
"-KMa95pUP3bKtnoQaPg4": {
"key": "-KMa95pUP3bKtnoQaPg4",
"time": "15:26",
"topic": "Linear Equations in two Variables",
"url": "https://www.youtube.com/watch?v=Wpr3tddDw9s",
"weight": 1
}
},
"-inner_test3": {
"-KMa8i5mU9HUapf-wGDU": {
"key": "-KMa8i5mU9HUapf-wGDU",
"time": "05:38",
"topic": "Measurement of volumes",
"url": "https://www.youtube.com/watch?v=mbFwgu4xx40",
"weight": 1
}
},
"inner_demo_test": {
"key1": {
"chapter": "Chapter 1",
"key": "key",
"weight": 1
},
"key2": {
"chapter": "Chapter 2",
"key": "-KMa5xai7vMQtaDZ0b31",
"weight": 2
}
}
}
}
NOTE : This is only 10% of total response.
The json you provided is valid, If you know the keys you can simply say
obj.getJSONObject("key");
If you don't know the keys, you can use iterator
JSONObject j=new JSONObject();
Iterator<String> iterator=j.keys();
while (iterator.hasNext())
{
String key=iterator.next();
JSONObject newObj= j.getJSONObject(key);
}
to fetch nested objects.
I'm trying to parse this json bellow, into a object named AlbumResponse that have another two objects inside, Album and PaginationInfo. Retrofit version 2.0
[
{
"id": "6",
"name": "King Stays King",
"artist_name":"Timbaland",
"image":""
},
{
"id": "7",
"name": "East Atlanta Santa 2",
"artist_name":"Gucci Mane",
"image":""
},
{
"id": "8",
"name": "The cuban connect",
"artist_name":"Phophit",
"image":""
},
{
"id": "9",
"name": "Shmoney Keeps",
"artist_name":"Calling",
"image":""
},
{
"id": "10",
"name": "Cabin Fever 3",
"artist_name":"Wiz khalifa",
"image":""
}
],
{
"nextPage": "http://private-ede172-mymixtapez1.apiary-mock.com/features/page_3/",
"itemsTotal": 10,
"page": 2,
"pagerMax": 2
}
Album class
public class Album {
long id;
String name;
#SerializedName("artist_name")
String artistName;
String image;
}
PaginationInfo class
public class PaginationInfo {
int page;
int pagerMax;
int nextPage;
int itemsTotal;
}
AlbumResponse, that have both classes above inside, and Album is a List
public class AlbumResponse {
public List<Album> albums;
public PaginationInfo paginationInfo;
}
The request
Call<AlbumResponse> responseCall = albumService.features();
responseCall.enqueue(new Callback<AlbumResponse>() {
#Override
public void onResponse(Response<AlbumResponse> response, Retrofit retrofit) {
if(response.isSuccess()) {
AlbumResponse albumResponse = response.body();
PaginationInfo paginationInfo = albumResponse.getPaginationInfo();
}
System.out.println();
}
#Override
public void onFailure(Throwable t) {
System.out.println(t.getMessage());
}
});
Interface
public interface AlbumService {
#GET("/features/")
Call<AlbumResponse> features();
}
The problem is that im getting a Throwable that contains:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $`
Please, can someone help me, i not found any answers in stackoverflow. Thanks.
The error says: the Parser expected a JSON-Object but it reads a JSON-array. To fix it (if you control the server) you should change the JSON String to something like this:
{
"albums" : [
{
"id": "6",
"name": "King Stays King",
"artist_name":"Timbaland",
"image":""
},
{
"id": "7",
"name": "East Atlanta Santa 2",
"artist_name":"Gucci Mane",
"image":""
},
{
"id": "8",
"name": "The cuban connect",
"artist_name":"Phophit",
"image":""
},
{
"id": "9",
"name": "Shmoney Keeps",
"artist_name":"Calling",
"image":""
},
{
"id": "10",
"name": "Cabin Fever 3",
"artist_name":"Wiz khalifa",
"image":""
}
],
"paginationInfo" : {
"nextPage": "http://private-ede172-mymixtapez1.apiary-mock.com/features/page_3/",
"itemsTotal": 10,
"page": 2,
"pagerMax": 2
}
}
Now it's a JSON-Object and is conform to your Java class.
If you cannot change the JSON on the backend, I would take it as row response and parse the albums Array and the PaginationInfo separately using GSON or manually.
Btw. you must change the nextPage type from int to String in the PaginationInfo class
Your JSON have a trouble in initial declaration.
According json.org:
JSON is built on two structures:
• A collection of name/value pairs. In various languages, this is
realized as an object, record, struct, dictionary, hash table, keyed
list, or associative array.
• An ordered list of values. In most
languages, this is realized as an array, vector, list, or sequence.
Try update your JSON to:
"albums": [
{
"id": "6",
"name": "King Stays King",
"artist_name":"Timbaland",
"image":""
},
{
"id": "7",
"name": "East Atlanta Santa 2",
"artist_name":"Gucci Mane",
"image":""
},
{
"id": "8",
"name": "The cuban connect",
"artist_name":"Phophit",
"image":""
},
{
"id": "9",
"name": "Shmoney Keeps",
"artist_name":"Calling",
"image":""
},
{
"id": "10",
"name": "Cabin Fever 3",
"artist_name":"Wiz khalifa",
"image":""
}
],
"pagination_info":
{
"nextPage": "http://private-ede172-mymixtapez1.apiary-mock.com/features/page_3/",
"itemsTotal": 10,
"page": 2,
"pagerMax": 2
}
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
}
For example : if the given below is json of the person's profile on facebook got thorugh facebook sdk login through android app , How we will get the School Name fron the education Field in th json data in android . Please Help
Data :
{
"id": "1464730016",
"name": "Ravi Tamada",
"first_name": "Ravi",
"last_name": "Tamada",
"link": "https://www.facebook.com/ravi8x",
"username": "ravi8x",
"birthday": "12/22/1988",
"hometown": {
"id": "112158005464147",
"name": "Baruva"
},
"location": {
"id": "102186159822587",
"name": "Chennai, Tamil Nadu"
},
"bio": "Author: www.androidhive.info\r\nCo-author: www.9lessons.info",
"work": [
{
"employer": {
"id": "179366562092719",
"name": "ByteAlly"
},
"location": {
"id": "102186159822587",
"name": "Chennai, Tamil Nadu"
},
"position": {
"id": "124917314217511",
"name": "Product Head"
}
]
}
],
"favorite_athletes": [
{
"id": "18620649907",
"name": "Virat Kohli"
}
],
"education": [
{
"school": {
"id": "131587206873093",
"name": "Raghu Engineering College (REC)"
},
"degree": {
"id": "140065339390579",
"name": "B.Tech"
},
"year": {
"id": "142963519060927",
"name": "2010"
},
"type": "Graduate School",
"classes": [
{
"id": "192259410803415",
"name": "2010",
"with": [
{
"id": "584960408",
"name": "Santosh Patnaik"
}
],
"from": {
"id": "584960408",
"name": "Santosh Patnaik"
}
}
]
}
],
"gender": "male",
"relationship_status": "Single",
"website": "www.androidhive.info\nwww.9lessons.info\nwww.twitter.com/ravitamada\nwww.about.me/rv",
"timezone": 5.5,
"locale": "en_US",
"languages": [
{
"id": "106059522759137",
"name": "English"
},
{
"id": "107617475934611",
"name": "Telugu"
},
{
"id": "112969428713061",
"name": "Hindi"
},
{
"id": "343306413260",
"name": "Tamil"
}
],
"verified": true,
"updated_time": "2012-03-02T17:04:18+0000"
}
JSONObject jsonResult = new JSONObject(jsonUser);
JSONArray data = jsonResult.getJSONArray("education");
if(data != null)
{
for(int i = 0 ; i < data.length() ; i++)
{
JSONObject c = data.getJSONObject(i);
String type = c.getString("type");
if(type.equalsIgnoreCase("college"))
{
JSONObject school = c.getJSONObject("school");
String id2 = school.getString("id");
String name2 = school.getString("name");
JSONObject year = c.getJSONObject("year");
String id_y = school.getString("id");
String name_y = school.getString("name");
}
}
}
Supposing that you've this json into a jsonObject that you retrieve as response, this is the way:
// Get jsonArray 'education' from main jsonObject
JSONArray jsonArrayEducation = jsonObject.getJSONArray("education");
JSONObject jsonSchool = jsonArrayEducation.getJSONObject("school");
Note that if you are interested only at the name, you can group the two lines above into
JSONObject jsonSchool = jsonObject.getJSONArray("education").getJSONObject("school");
// get school name
String schoolName = jsonSchool.getString("name");
I am working on app in which I have to parse below JSON.
Anyone can anyone tell me how to do this?
{
"navigation_entries": {
"home": {
"children": [
"favorites",
"calendar",
"offers",
"wineries",
"dining",
"lodging",
"things_to_do",
"weather",
"settings"
],
"banner_image": "home_page_banner",
"icon": {
"small": "icon_home_small",
"large": "icon_home_large"
},
"type": "home_page",
"forward_icon": {
"small": "icon_right_arrow_small",
"large": "icon_right_arrow_large"
},
"link_name": "Home"
},
"wineries": {
"display_name": "Wineries",
"icon": {
"small": "icon_wineries_small",
"large": "icon_wineries_large"
},
"line_template": "wineries_list_template",
"forward_icon": {
"small": "icon_right_arrow_small",
"large": "icon_right_arrow_large"
},
"link_name": "Wineries",
"type": "leaf_list",
"leaf_template": "wineries_leaf_template",
"section": "wineries"
},
"dining": {
"display_name": "Dining",
"icon": {
"small": "icon_dining_small",
"large": "icon_dining_large"
},
"line_template": "dining_list_template",
"forward_icon": {
"small": "icon_right_arrow_small",
"large": "icon_right_arrow_large"
},
"link_name": "Dining",
"type": "leaf_list",
"leaf_template": "dining_leaf_template",
"section": "dining"
},
"offers_dining": {
"display_name": "Offers => Dining",
"list_name": "Dining",
"line_template": "offers_dining_list_template",
"type": "leaf_list",
"leaf_template": "offers_dining_leaf_template",
"forward_icon": {
"small": "icon_right_arrow_small",
"large": "icon_right_arrow_large"
},
"section": "offers_dining"
},
"favorites": {
"display_name": "Favorites",
"icon": {
"small": "icon_favorites_small",
"large": "icon_favorites_large"
},
"type": "favorites",
"forward_icon": {
"small": "icon_right_arrow_small",
"large": "icon_right_arrow_large"
},
"link_name": "Favorites"
},
"offers": {
"display_name": "Offers",
"children": [
"offers_wineries",
"offers_dining",
"offers_lodging",
"offers_things_to_do"
],
"icon": {
"small": "icon_offers_small",
"large": "icon_offers_large"
},
"type": "navigation_list",
"forward_icon": {
"small": "icon_right_arrow_small",
"large": "icon_right_arrow_large"
},
"link_name": "Offers"
}
},
"type": "navigation"
}
You can use this website to format your JSON string in a in an easier way to view it.
Android provides an appropiate library to do what you want.
This is the manual page you need to comprehend how to use Android JSON API.
And here you can see a tutorial to understand how to parse JSON string.
{
"glossary": {
"title": "example glossary",
"GlossDiv": {
"title": "S",
"GlossList": {
"GlossEntry": {
"ID": "SGML",
"SortAs": "SGML",
"GlossTerm": "Standard Generalized Markup Language",
"Acronym": "SGML",
"Abbrev": "ISO 8879:1986",
"GlossDef": {
"para": "A meta-markup language, used to create markup languages such as DocBook.",
"GlossSeeAlso": ["GML", "XML"]
},
"GlossSee": "markup"
}
}
}
}
}
If the example above is your string, you can parse it passing it to the JSONObject constructor:
String jsonString = "...."; // the above string
try {
JSONObject obj = new JSONObject(jsonString);
} catch (JSONException e) {
// This exception is thrown if jsonString is not correctly formatted
}
Now, if you want to get the JSONObject labled "GlossList", inside the string above, you can do this:
JSONObject glossList = obj.getJSONObject("glossary").getJSONObject("GlossDiv").getJSONObject("GlossList");
There is also another possibility: you can also obtain some JSONArray. In our example, the array GlossSeeAlso:
JSONArray glossSee = glossList.getJSONObject("GlossEntry").getJSONObject("GlossDef").getJSONArray("GlossSeeAlso");
To get directly a value of this array, you can use the method getString(int i); if the contend of the array is a JSONObject, you can use the method getJSONObject(int i). You can also use the method getString(String lable) to get directly a string in a JSONObject:
String title = glossDive.getString("title");
String firstElement = glossSee.getString(0);
Other examples are available in the official JSON site.
You can use JSONObject and JSONTokener like this:
String json = "{"
+ " \"query\": \"Pizza\", "
+ " \"locations\": [ 94043, 90210 ] "
+ "}";
JSONObject object = (JSONObject) new JSONTokener(json).nextValue();
String query = object.getString("query");
JSONArray locations = object.getJSONArray("locations");
jsonlint.com has a very good json formatter. this should make your text easily understandable.
for parsing this data, you can use JSONObject (org.json.JSONObject)