how to create a pojo class with dynamic key for arrayname - android

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.

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.

How to dynamically parse json response where key is changing dynamically

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;
}

How to parse this JSON file to some ArrayList<String>?

in the past i have already parsed a json file from url to local sqlite database and the json source was like the following one:
[
{
"origin": "accommodation",
"parent": "",
"en": "Accommodation"
},
{
"origine": "book",
"parent": "shopping",
"en": "Book"
},
{
"origin": "university",
"parent": "education",
"en": "University"
}
]
But now it seems to be different. I validate the following json file so i'm sure it is a valid json, but it is formatted in a different way, so i do not know how to parse it in the right way. In addition this time i would put the content in an ArrayList. Here is the json file:
{
"city1": {
"item1": {
"score": 6196.58,
"step": 0.00423,
"name": "User 1",
"form": "yellow"
},
"item2": {
"score": 106.86,
"step": 2.5822,
"name": "User 2",
"form": "yellow"
},
"item3": {
"score": 671.48,
"step": 0.387,
"name": "User 3",
"form": "yellow"
},
},
"misc": {
"online_users": {
"kind1": 18,
"kind2": 3
},
"ops": [
""
]
},
"city2": {
"item1": {
"score": 6196.58,
"step": 0.00405,
"name": "User 1",
"form": "yellow"
},
"item2": {
"score": 179563.93,
"step": 0.000138,
"name": "User 2",
"form": "yellow"
},
"min_size": {
"line": 10
},
"out_of_sync": [
"0e888069530497506433b5f0cacb",
"b428fa3a9b9e13cf8b26196bfcc7",
"f42442a2e46523f059809f83f1a9"
],
},
}
Can you tell me how to handle these values and how to put in some arraylist?
There are several ways to do this, but I'll post the way I feel like makes the most sense. If you don't mind putting this in separate arrays you can do this:
String stringOfJSONCode = <read in the JSON here>;
JSONObject json = new JSONObject(stringOfJSONCode);
Iterator<String> iter = json.keys();
while (iter.hasNext()) {
String key = iter.next();
try {
Object value = json.get(key);
} catch (Exception e) {
}
}
You need to use an iterator to loop through a JSONObject. You could use any other loop to loop through JSONArrays. This will iterate through the outer objects, like city1, misc, city2. The key will be either city1, misc, or city2.
If you want to get those, just add this within the 'try'
JSONObject object = json.getJSONObject(key);
or
JSONArray array = json.getJSONArray(key);
depending on what you're trying to get. Once you have these, you can do the following:
JSONObject city1 = object.getJSONObject("item1");
List<String> jsonList = new ArrayList<String>();
jsonList.add(object.getDouble("score"));
jsonList.add(object.getDouble("step"));
jsonList.add(object.getString("name"));
jsonList.add(object.getString("form"));
If you are not sure if it will be item1 or whatever, you can iterate through it again using the iterator and add each item in dynamically. Also you can make another try-catch, try to get a JSONArray, if it is not an array it will go in the catch, and then iterate through the object.
You could also make a hashmap or 2D array to add everything in the same array.
Hope this helps
Why don't you let jackson mapper do it's magic?
The only thing you'll need then would be appropriate DTO classes.

Android JSON parsing from google-shopping-api error

I decided I wanted to try using the Google shopping API out last week, but I had no idea how to parse JCON objects.
After much searching here I was able to get the product information for an item! However, I cannot narrow down to just a string in the product. So for example I want to just get the title of a product.
I have the following:
jsonString:
{
"kind": "shopping#products",
"etag": "\"GKsxsRlaBDslDpMe-MT1O7wqUDE/dMvQ5Pu2C806fWZJbNJ0GjdesJs\"",
"id": "tag:google.com,2010:shopping/products",
"selfLink": "https://www.googleapis.com/shopping/search/v1/public/products?country=US&restrictBy=gtin:051500240908&startIndex=1&maxResults=25",
"totalItems": 3,
"startIndex": 1,
"itemsPerPage": 25,
"currentItemCount": 3,
"items": [
{
"kind": "shopping#product",
"id": "tag:google.com,2010:shopping/products/7585088/9884865157760252836",
"selfLink": "https://www.googleapis.com/shopping/search/v1/public/products/7585088/gid/9884865157760252836",
"product": {
"googleId": "9884865157760252836",
"author": {
"name": "Southeastern Delivery",
"accountId": "7585088"
},
"creationTime": "2011-07-25T00:15:58.000Z",
"modificationTime": "2012-02-11T09:29:00.000Z",
"country": "US",
"language": "en",
"title": "Jif Peanut Butter, Creamy",
"description": "Jif Creamy Peanut Butter. Fresh Roasted Peanut Taste. Look for the flavor seal. Contains no preservatives. No refrigeration required.",
"link": "http://www.southeasterndelivery.com/Jif_Peanut_Butter_00051500240908/",
"brand": "Jif Peanut Butter",
"condition": "new",
"gtin": "00051500240908",
"gtins": [
"00051500240908"
],
"inventories": [
{
"channel": "online",
"availability": "inStock",
"price": 15.64,
"shipping": 1.56,
"currency": "USD"
}
],
"images": [
{
"link": "http://www.southeasterndelivery.com/images/ProductImages/00051500240908.jpg"
}
]
}
},
],
"requestId": "0CLGzkcKVo64CFRDd5wod4mMAAA"
}
I have the following code in my android app to parse it:
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray itemsArray = jsonObject.getJSONArray("items");
JSONObject productObject = itemsArray.getJSONObject(0);
//String productTitle = productObject.getString("title");
//tv.setText(productTitle);
tv.setText(productObject.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
tv.setText("JSONOBJECT Error: " + e);
e.printStackTrace();
}
setContentView(tv);
The TextView on my Android app will now display (obviously not indented I did that for easy reading):
"product": {
"googleId": "9884865157760252836",
"author": {
"name": "Southeastern Delivery",
"accountId": "7585088"
},
"creationTime": "2011-07-25T00:15:58.000Z",
"modificationTime": "2012-02-11T09:29:00.000Z",
"country": "US",
"language": "en",
"title": "Jif Peanut Butter, Creamy",
"description": "Jif Creamy Peanut Butter. Fresh Roasted Peanut Taste. Look for the flavor seal. Contains no preservatives. No refrigeration required.",
"link": "http://www.southeasterndelivery.com/Jif_Peanut_Butter_00051500240908/",
"brand": "Jif Peanut Butter",
"condition": "new",
"gtin": "00051500240908",
"gtins": [
"00051500240908"
],
"inventories": [
{
"channel": "online",
"availability": "inStock",
"price": 15.64,
"shipping": 1.56,
"currency": "USD"
}
],
"images": [
{
"link": "http://www.southeasterndelivery.com/images/ProductImages/00051500240908.jpg"
}
]
}
Now if you notice in my Java code I have two lines commented out. If I uncomment those lines and then comment the line:
tv.setText(productObject.toString());
tv gets set to this error: "JSONOBJECT Error: org.json.JSONEception: No value for title". I am not sure why this is true because clearly their is a title in the productObject.
Any help would be great!
I'm using json-smart in my project. It is very small and very fast. To convert your JSON from Sting to the actual object use JSONObjet json = (JSONObject)JSONValue.parse(rawString);
When you have JSONObject you treat it just like a Map. So String title = (String) json.get("title")
You are missing a level of information in your code. The JSON array contains items, which contains products, which have a title.
Your code should look like:
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray itemsArray = jsonObject.getJSONArray("items");
JSONObject itemObject = itemsArray.getJSONObject(0);
JSONObject productObject = itemObject.getJSONObject("product");
String productTitle = productObject.getString("title");

Categories

Resources