How to show JSON parsed data in expandable listview? - android

I am using AndroidHive method to display a custom expandable listview. It has a static data inserted. but in my app , i am receiving a json data and i am unable to parse it in a way to display it inside the expandable listview.
JSON data I recieve is
{
"success": 1,
"Message": "User exist",
"category": [{
"major_item_id": "1",
"Major_item_name": "Cement"
}, {
"major_item_id": "15",
"Major_item_name": "Wire"
}],
"subcategory": [{
"major_item_id": "1",
"name_item":"abc1"
}, {
"major_item_id": "1",
"name_item":"pqrs2"
}, {
"major_item_id": "15",
"name_item":"lmn"
}, {
"major_item_id": "15",
"name_item":"xyz"
}]}
What I want to is an expandable listview in format :
Cement //listHeader
-abc1 // child items
-pqrs2 // child items
Wire
-lmn
-xyz

An JSON file consist of many components. Here is the table defining the components of an JSON file and their description
Array([)
In a JSON file , square bracket ([) represents a JSON array
Objects({)
In a JSON file, curly bracket ({) represents a JSON object
Key
A JSON object contains a key that is just a string. Pairs of key/value make up a JSON object
Value
Each key has a value that could be string , integer or double e.t.c
Each implementations are different according to the json format that you have been used. You can easily find too many examples on internet.
http://www.tutorialspoint.com/android/android_json_parser.htm

You can use Gson to convert the JSON to an object like this:
Gson gson = new Gson();
Type listType = new TypeToken<YourObject>() {}.getType();
YourObject obj = gson.fromJson(getCurrentChat(), listType);
Once you have the correct object you can use the corresponding values to update your ExpandableListView.

Related

How to fetch multilevel JSON using volley?

My JSON Example where i am willing to get data from every "show" Array
{
"score":17.873907,
"show":{
"id":139,
"url":"http://www.tvmaze.com/shows/139/girls",
"name":"Girls",
"type":"Scripted",
"language":"English",
"genres":[
"Drama",
"Romance"
],
"status":"Ended",
"runtime":30,
"premiered":"2012-04-15",
"officialSite":"http://www.hbo.com/girls",
"schedule":{
"time":"22:00",
"days":[
"Sunday"
]
},
"rating":{
"average":6.7
},
"weight":81,
"network":{
"id":8,
"name":"HBO",
"country":{
"name":"United States",
"code":"US",
"timezone":"America/New_York"
}
},
"webChannel":null,
"externals":{
"tvrage":30124,
"thetvdb":220411,
"imdb":"tt1723816"
},
"image":{
"medium":"http://static.tvmaze.com/uploads/images/medium_portrait/31/78286.jpg",
"original":"http://static.tvmaze.com/uploads/images/original_untouched/31/78286.jpg"
},
"summary":"<p>This Emmy winning series is a comic look at the assorted humiliations and rare triumphs of a group of girls in their 20s.</p>",
"updated":1600633829,
"_links":{
"self":{
"href":"http://api.tvmaze.com/shows/139"
},
"previousepisode":{
"href":"http://api.tvmaze.com/episodes/1079686"
}
}
}
}
The Request Code I am using which is giving me the response nicely but i cannot parse the response to JSONObject
Error Showing
org.json.JSONException: Value show of type java.lang.String cannot be
converted to JSONObject
When you are passing JSONObject("show") , it is trying to convert 'show' string to json Obviously it isn't json stirng so it is throwing error;
It should be something like :
JSONObject obj = new JSONObject(response);
JSONObject obj_show= obj.getJSONObject("show"));
Log.d("show",obj_show.getJSONObject("show").toString());
The Solution Was "I Used Nested Model Class to Load Data, and that worked like a charm!"

How to post Json Array using retrofit in android?

I am not able to post Json array from my add to cart list using retrofit. User will choose the products and then add to cart. Ineed save that data using sqlite db. Final order confirm state - I want to send all products (list) to server like this format code. I searched on google and can't find any solution.
JsonArray datas = new JsonArray();
JsonObject object = new JsonObject();
[
{
"name": "Phone",
"quantity": 50,
"price": 30000
},
{
"name": "Computer",
"quantity": 10,
"price": 15000
}
]
this is very simple just do like this:-
#POST("yourApiEndPoint")
Call<YourPojoClass> yourMethodName(#Query("data") JSONArray jsonArray);

Gson - is it possible int fields in quote (") when create json from object?

I am using gson lib to create json from objects. Backend developers are asking to create all values should be in "" quotes event int/long/boolean fields. For example my json looks like that:
{
"age": 26,
"email": "norman#futurestud.io",
"isDeveloper": true,
"name": "Norman"
}
-> i need the following format:
{
"age": "26",
"email": "norman#futurestud.io",
"isDeveloper": "true",
"name": "Norman"
}
Should i change all my fields from int to String or is there any way to do that? Thanks in advance!
To achieve this only way is to store Int as String and then converting the Data class to json String.As Gson use auto typecasting, you can't tell Gson to convert int to String and give you json.
Create the POJO according to your output json that is the only go.
Your code is JavaScript object literal, not a JSON.
Well try this out!
var obj = {"age": 26,"email": "norman#futurestud.io", "isDeveloper":
true, "name":
"Norman"};
for (var k in obj) {
if (obj.hasOwnProperty(k))
{
obj[k] = String(obj[k]);
}
}

How to parse json array of objects with retrofit which has different data types for same key

I am getting a json array in API response which has different data types (String, Integer and Array) in same key (value) but getting error while parsing them with Retrofit:
{
"custom_attributes": [
{
"attribute_code": "description",
"value": "<p>Product Features:</p>\r\n<ul>\r\n<li>100% cotton</li>\r\n<li>Round neck</li>\r\n<li>Short sleeve</li>\r\n<li>Plastisol printing technique</li>\r\n<li>Small label on side of sleeve</li>\r\n</ul>"
},
{
"attribute_code": "short_description",
"value": "<p>100% cotton round neck short sleeve tee with plastisol printing technique</p>"
},
{
"attribute_code": "category_ids",
"value": [
"3",
"125"
]
},
{
"attribute_code": "special_price",
"value": true
},
{
"attribute_code": "size",
"value": 4
}
]
}
I can't understand what is the need of keeping your JSON format like this.
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.
Tell me your requirement i will update your JSON and this problem will be solved once you will start getting updated JSON from erver.
Firstly store response in string like this
String response =apiresponse;
Then try this parsing methood without any thirdparty
get jsonobject from string response
JSONObject object=new JSONObject(response);
get jsonarray from json object
JSONArray jsonArray=object.getJSONArray("custom_attributes");
iterate json array till its length
for(int i=0;i<jsonArray.length;i++){
JSONObject newobject=jsonArray.getJSONObject(i);
Boolean valueBoolean;
String valueString;
String attribute_code=newObject.getString("attribute_code");
Object value=newObject.get("value");// get **value** key data in object
now check datatype of value key
if(value instanceof String){
valueString=value.toString(); //if value found string store in in value String
}else if(value instanceof Boolean){
valueBoolean=(Boolean)value; //if value found Boolean store it in valueBoolean
}
}
In the last its upto you , you may simply create a custom arraylist and save all details with datatype key

(Android) Java: JSON Parsing

I found a lot of tutorials here, how to parse JSON Data of an JSON Array.
But my JSON File is a little bit complicate (for me). It has the following structure:
JSON File (excerpt)
{
"data": {
"schedule_id": {
"12": {
"name": "CP",
"d_id": [
"7"
]
},
"17": {
"name": "WT",
"d_id": [
"88",
"14"
]
}
}
}
}
Java Code (excerpt)
Info: I've parsed the json into "json" using HTTP GET in another Activity.
JSONObject dataJsonData = json.getJSONObject("data").getJSONObject("schedule_id");
Now I would parse through the ids using a "for"-loop:
ArrayList<String> parsedNameList = new ArrayList<String>();
for (int i = 0; i < idontknow; i++) {
String s = new Integer(i).toString();
parsedNameList.add(dateJsonData.getJSONObject(i).getString("name"));
}
This would add each value of "name" to the ArrayList.
But there are 2 problems:
1. The "schedule_id"s are messed up and incomplete. For example, there is no id "0" and, like in given json, the ids "13, 14, 15, 16" are missing.
2. The "schedule_id"s will be changed every day and will be mixed.
So I don't think, that I can use the predefined integer "i" because some integers aren't a "schedule_id". I could use this loop and would ignore empty entries in the ArrayList, but the JSON contains more than 200 ids - I think it would be more efficient, if there is another way to parse through this json.
I found some informations of the getJSONArray method, but the "d_id"s are Arrays - not the "schedule_ids".
Does anyone has an idea? Is there maybe a placeholder for the parameter of the getString method?
PS: Excuse my english, I'm from germany :)
I think this should work
Iterator keys = dataJsonData.keys();
while(keys.hasNext()) {
// loop to get the dynamic key
String currentDynamicKey = (String)keys.next();
// get the value of the dynamic key
String currentDynamicValue = dataJsonData .getString(currentDynamicKey);
parsedJsonList.add(currentDynamicValue );
}
Source: How to parse a dynamic JSON key in a Nested JSON result?
According to your context, it is better to change the json structure,if you have access to web service.
Request for json structure to be like this,
{
"data":{
"schedule":[
{
"id":12,
"name":"CP",
"d_id":[
"7"
]
},
{
"id":12,
"name":"CP",
"d_id":[
"7",
"88"
]
},
{
"id":200,
"name":"AT",
"d_id":[
"7",
"88"
]
}
]
}
}
Otherwise too much iteration can slow down you CPU.

Categories

Resources