How to dynamically parse json response where key is changing dynamically - android

My json response is like
"answers": [{
"data": [
{
"currency": "EUR/JPY",
"rate": "122.593",
"timestamp": "1497524449141"
},
{
"currency": "EUR/CHF",
"rate": "1.08779",
"timestamp": "1497524449234"
},
{
"currency": "USD/CAD",
"rate": "1.32772",
"timestamp": "1497524449235"
},
{
"currency": "AUD/USD",
"rate": "0.75875",
"timestamp": "1497524449148"
},
{
"currency": "GBP/JPY",
"rate": "140.248",
"timestamp": "1497524449230"
}
],
"metadata": {"count": 60},
"actions": [{
"type": "table",
"columns": {
"currency": "Valuta",
"rate": "Quota"
},
"count": -1
}]
}],
Here action Json array has json object columns. Key currency and rate name is dynamic i.e it may have other name like game and goal or anything else and also number of key may also change. Accordingly key in data json array also change. Data json array use same key name.

You could use Gson library and parse data object as Array of HashMaps.
Updated:
Here is a small code example (I simplefied your JSON a bit):
­
private void parse() {
String json = "[{\"data\":[{\"currency\":\"EUR/JPY\",\"rate\":\"122.593\",\"timestamp\":\"1497524449141\"},{\"currency\":\"EUR/CHF\",\"rate\":\"1.08779\",\"timestamp\":\"1497524449234\"},{\"currency\":\"USD/CAD\",\"rate\":\"1.32772\",\"timestamp\":\"1497524449235\"},{\"currency\":\"AUD/USD\",\"rate\":\"0.75875\",\"timestamp\":\"1497524449148\"},{\"currency\":\"GBP/JPY\",\"rate\":\"140.248\",\"timestamp\":\"1497524449230\"}],\"metadata\":{\"count\":60},\"actions\":[{\"type\":\"table\",\"columns\":{\"currency\":\"Valuta\",\"rate\":\"Quota\"},\"count\":-1}]}]";
Type type = new TypeToken<List<DataObject>>(){}.getType();
List<DataObject> list = new Gson().fromJson(json, type);
for (DataObject object : list) {
for (HashMap<String, String> map : object.data) {
Log.e("mapItemStart", "===============");
for (String item : map.keySet()) {
Log.e("mapItem", item + " -> " + map.get(item));
}
Log.e("mapItemEnd", "===============");
}
}
}
public static class DataObject {
public List<HashMap<String, String>> data;
}

Related

Android - Parse a Nested JSON array with Volley

I am really new to JSON Parsing and learning everyday.
I have a specific JSON response I have to parse but I am finding no luck doing it.
I am using Volley for Parsing Request.
Here is my response:
{
"error": false,
"message": "Favourties fetched successfully",
"code": 200,
"data": [
{
"id": "5f1980f8c42e1f60854c57e4",
"type": 1,
"status": 1,
"favourite": {
"_id": "5f118057f44ebd1cead089db",
"firstName": "Bilal",
"lastName": "Khan",
"businessName": "Master Paint",
"image": "https://welist-assets.s3.us-west-2.amazonaws.com/profile_images/1592383845941-default_avatar.png"
},
"createdAt": "2020-07-23T12:22:16.731Z",
"updatedAt": "2020-07-23T12:22:16.731Z"
},
{
"id": "5f198084c42e1f60854c57e2",
"type": 3,
"status": 1,
"favourite": {
"images": [],
"_id": "5f12d5345478a53584eca98b",
"name": "Water Paint7"
},
"createdAt": "2020-07-23T12:20:20.680Z",
"updatedAt": "2020-07-23T12:20:20.680Z"
}
]
}
I am able to get the Array which contains 2 object, but I am unable to get the data inside the nested favorites.
try {
Log.d("Onresponse", response);
//converting the string to json array object
JSONObject obj = new JSONObject(response);
JSONArray array = obj.getJSONArray("data");
//traversing through all the object
for (int i = 0; i < array.length(); i++) {
//getting product object from json array
JSONObject favorites = array.getJSONObject(i);
Log.d("lenght", favorites.getString("status"));
//adding the product to product list
favoriteList.add(new FavoriteVendorsModel(
favorites.getString("firstName"),
favorites.getString("lastName"),
favorites.getString("businessName"),
favorites.getString("image")
));
}
Here is my method.
You have skipped one level of nesting. By calling array.getJSONObject(i) you get:
{
"id": "5f1980f8c42e1f60854c57e4",
"type": 1,
"status": 1,
"favourite": {
"_id": "5f118057f44ebd1cead089db",
"firstName": "Bilal",
"lastName": "Khan",
"businessName": "Master Paint",
"image": "https://welist-assets.s3.us-west-2.amazonaws.com/profile_images/1592383845941-default_avatar.png"
},
"createdAt": "2020-07-23T12:22:16.731Z",
"updatedAt": "2020-07-23T12:22:16.731Z"
}
And you are trying to call directly on that object next getString methods:
favorites.getString("firstName");
favorites.getString("lastName");
favorites.getString("businessName");
favorites.getString("image");
When actually you must first get JSONObject named favourite and then call these getString method on it:
JSONObject favorite = favorites.getJSONObject("favourite");
favorite.getString("firstName");
favorite.getString("lastName");
favorite.getString("businessName");
favorite.getString("image");

set value of multidimensional json array to string in android using volley

I am trying Expandable Recycler view using Volley and thoughtbot expandablerecyclerview. Please see my JSON Array below.
{
"Ravi Shankar": [{
"staffname": "Ravi Shankar",
"taskname": "tesing1 task",
"id": "1"
}, {
"staffname": "Ravi Shankar",
"taskname": "testing 2 task",
"id": "2"
}, {
"staffname": "Ravi Shankar",
"taskname": "IMAGE TESTING",
"id": "4"
}, {
"staffname": "Ravi Shankar",
"taskname": "IMAGE NEW",
"id": "5"
}],
"Ritesh": [{
"staffname": "Ritesh",
"taskname": "testing3 task",
"id": "3"
}]
}
This array was group by employee name. I need to get the group name as a string and child array in a loop.
I tried below code but it's not given as I expected.
for(int i=0;i<response.length();i++){
JSONObject jsonObject = response.getJSONObject(i);
String tstaffname = jsonObject.has("staffname")?jsonObject.getString("staffname"):"";
String ttaskname = jsonObject.has("taskname")?jsonObject.getString("taskname"):"";
String tid = jsonObject.has("id")?jsonObject.getString("id"):"";
//addTasks(tstaffname,ttaskname);
Log.e("EmpName", ttaskname);
tasksNames.add(new TasksName(ttaskname));
StaffName staffName = new StaffName(tstaffname, tasksNames);
staffNames.add(staffName);
}
Please comment for any clarification.

Sorting JSON data that comes from Retrofit2 on API Level 15

i am new in retrofit . i was using Comparator for sorting my json but i find out that this code Added from api 24 . How can i sort my data for api 15 .
I dont want to sort data before getting it in mysql and i want to do it by android coding .
this is my sample data
[
{
"id": "1",
"name": "name1",
"lastname": "lastname1",
"rank": "1",
},
{
"id": "2",
"name": "name2",
"lastname": "lastname2",
"rank": "10",
},
{
"id": "20",
"name": "name20",
"lastname": "lastname20",
"rank": "105",
}
}
and some other question :
how do i delete coming data from retrofit that have one parameter null?
how to get the object that has rank 105?
Get your response in any model like
Like
List data;
where Response is
public class Response {
public int id;
public String name;
boolean isValid() {
return id > 0 && !TextUtils.isEmpty(name);
}
}
and filter invalid response like
ListIterator iterator = data.listIterator();
while (iterator.hasNext()) {
Response response = (Response) iterator.next();
boolean success = response.isValid();
if (!success) {
iterator.remove();
}
}

how to create a pojo class with dynamic key for arrayname

I am working with Rxandroid and retrofit. I have a json with dynamically changing array name like this,
{
"2016-10-02": [
{
"name": "foo",
"id": "1",
"category": "bar"
},
{
"name": "foo",
"id": "2",
"category": "bar"
},
{
"name": "foo",
"id": "3",
"category": "bar"
},
{
"name": "foo",
"id": "4",
"category": "bar"
}
],
"2016-10-01": [
{
"name": "foo",
"id": "5",
"category": "bar"
},
{
"name": "foo",
"id": "6",
"category": "bar"
},
],
"2016-10-03": [
{
"name": "foo",
"id": "5",
"category": "bar"
}
]
}
The date key name for each array changes automatically and the number of array changes. In this example there are 3 arrays with date key. But the number of these array varies.
I have been through various links in stackoverflow but could not solve the issue.
Use JSONObject keys() to get the key and then you could iterate each key to get the dynamic values :
JSONObject object = new JSONObject("your response string")
Iterator keys = object.keys();
//Let's consider your POJO class is CategoryClass
// Let's take HashMap to store your POJO class for specific KEY
HashMap<String, ArrayList<CategoryClass>> mMap = new HashMap<String, ArrayList<CategoryClass>>();
while(keys.hasNext()) {
// here you will get dynamic keys
String dynamicKey = (String)keys.next();
// get the value of the dynamic key
JSONArray dynamicValue = object.getJSONArray(currentDynamicKey);
//Let's store into POJO Class and Prepare HashMap.
ArrayList<CategoryClass> mCategoryList = new ArrayList<CategoryClass>();
for(int i = 0 ; i < dynamicValue.length(); i++){
CategoryClass mCategory = new CategoryClass();
mCategory.setName(dynamicValue.getString("name"));
mCategory.setId(dynamicValue.getString("id"));
mCategory.setCategory(dynamicValue.getString("category"));
mCategoryList.add(mCategory);
}
//Add Into Hashmap
mMap.put(dynamicKey, mCategoryList);
}
From my point of view,this format is not recommended.The date should be value such as "date":"2016-10-01" instead of json key.

How can i parse a enum value through GSon parser in android application

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"));

Categories

Resources