Dynamic Json Parsing Using Gson Android - java

I have a json as mentioned below.
{
"product": [
{
"classification": "abc",
"ABC": [
{
"classification": "abc",
"name": "abc new product one",
"price": "10775.0000",
},
{
"classification": "abc",
"name": "abc new product two",
"price": "12725.0000",
}
]
},
{
"classification": "def",
"DEF": [
{
"classification": "def",
"name": "def product one",
"price": "728.0000",
},
{
"classification": "def",
"name": "def product two",
"price": "1263.0000",
},
]
}
],
"status": "OK",
"message": "success"
}
In the above json, the key in capital letter is dynamic
(Ex: ABC, DEF)
. I've created pojo class as below:
public class ProductResponse{
private String status;
private String message;
private List<Products>;
Getters And Setters
}
public class Products{
private String classification;
}
I'm struggling to write the next part in Products pojo class, As the keys which are in capitals
(Ex: ABC, DEF)
are dynamic. I am using volley library for getting the data and for parsing I'm using gson library. Please help me out.

You can't have a dynamic name. the reason being is the name in your json needs to be linked to an attribute in your object.
I recommend you to add a "classification" attribute in your json and your model as following :
{
"type": "def",
" results": [
{
"name": "def product one",
"price": "728.0000",
},
{
"name": "def product two",
"price": "1263.0000",
},
]
}
public final class ProductResponse{
private String status;
private String message;
private List<Products> product = new Arraylist<>();
// Getters And Setters
}
public final class Products{
private String type; // type of product // ABC or DEF
private List<Result> results = new Arraylist<>();
// Getters And Setters
}
public final class Result{
private String name;
private String price;
// Getters And Setters
}
Your products class has now a list of results associated to a classification !
Hope it helps !

Your problem is the dynamic key, which I found is not dynamic. As I can see, For each element in the product array, the classification key's value is the next key. Only difference is that they are in capital letters.
{
"classification": "def",
"DEF": [
{
"classification": "def",
"name": "def product one",
"price": "728.0000",
},
{
"classification": "def",
"name": "def product two",
"price": "1263.0000",
},
]
}
As in, here "classification": "def" and the next key is DEF. What I would do here is get the value of classification key, capitalize all the letters in the string and then use it as the key.

Related

how to serialize a specific json format

I need to set json in a format provided below.
"Tyre": {
"title": "Tyre",
"cls": "TyreCondition",
"items": [
{
"firstItem": [
{
"title": "Front right tyre",
"value": "50%",
"subValue": "30,000 km Approx"
}
],
"secItem": [
{
"title": "title",
"value": "Front right tyre tread - 50%"
},
{
"title": "title",
"value": "Front right tyre tread - 50%"
}
]
}
]
}
class that i have created for this is looks like:
private String title;
private String cls;
#SerializedName("firstItem")
private List<UsedCarInspectionInfo> items;
#SerializedName("secItem")
private List<UsedCarTyreImage> imageList;
//getter and setter
when i run this code with this class structure, I am getting the json like-
"Tyre": {
"title": "Tyre",
"cls": "TyreCondition",
"firstItem": [
{
"title": "Front right tyre",
"value": "50%",
"subValue": "30,000 km Approx"
}
],
"secItem": [
{
"title": "title",
"value": "Front right tyre tread - 50%"
},
{
"title": "title",
"value": "Front right tyre tread - 50%"
}
]}
Any idea how i can get the firstItem and secItem array in Items array?
You get no items key in your JSON, because you override the items field in your Java class with #SerializedName.
You need something like this:
String title;
String cls;
List<Item> items;
static class Item {
List<FirstItem> firstItem;
List<SecItem> secItem;
}
static class FirstItem {
String title;
String value;
String subValue;
}
static class SecItem {
String title;
String value;
}

How to ignore wrap element when parse json to dto

I have a json like this
{
"135": {
"id": "135",
"name": "My Awesome Washing Machine!",
"powerswitch": {
"available": "true",
"state": "on",
"reachable": "true",
"locked": "false"
},
"reference": {
"id": "4",
"name": "Lave-linge",
"category_id":"2"
}
},
"491": {
"id": "491",
"name": "My Fridge",
"powerswitch": {
"available": "true",
"state": "on",
"reachable": "false",
"locked": "false"
},
"reference": {
"id": "1",
"name": "Réfrigérateur",
"category_id":"1"
}
}
}
And here is my dto:
public class Device {
private String id;
private String name;
private DevicePowerswitch powerswitch;
private DeviceReference reference;
//getter, setter
}
The question is how can I parse json to a list of device.
Note that there is a non-static id value wrapper in this above json.
You'll need to parse the JSON into a JsonNode, and then iterate over the children. The nodes you pull out as a result can then be mapped using an ObjectMapper to Device instances.
ObjectMapper mapper = new ObjectMapper();
final JsonNode jsonNode = mapper.readTree(JSON);
for (JsonNode node : jsonNode)
{
final Device device = mapper.convertValue(node,
Device.class);
// do something with the device
}

GSON deserialization of object arrays

I have a class with the following attributes
public class JenkinsServer
{
private String url;
private String mode;
private String nodeName;
private String nodeDescription;
private String description;
private boolean useSecurity;
private boolean quietingDown;
private JenkinsServerView primaryView;
private List< JenkinsJob > jobs;
private List< JenkinsServerView > views;
}
Now I want GSON to deserialize/map a json document to it. It works well, except for my lists - they are empty. The json document looks as follows (snippet):
"jobs": [
{
"name": "AnotherJob",
"url": "https://build.example.com/jenkins/job/AnotherJob/",
"color": "disabled"
},
{
"name": "AnotherJob2",
"url": "https://build.example.com/jenkins/job/Build%20CI%20Build/",
"color": "blue"
},
"views": [
{
"name": "-All Views",
"url": "https://build.example.com/jenkins/view/-All%Views/"
},
{
"name": "Alle",
"url": "https://build.example.com/jenkins/"
},
The mapping works, even for the single instance of
JenkinsServerView primaryView
but not for the Lists. I'm starting the mapping this way:
Gson gson = gsonBuilder.create();
JenkinsServer server = gson.fromJson( reader, JenkinsServer.class );
looks your json data that you are trying to parse is invalid.
In your json jobs and views are arrays and both of them doesn't have the closing brace at the end.
The valid json will be as follows: (Observe the closing braces at the end of the array)
{
"jobs": [
{
"name": "AnotherJob",
"url": "https://build.example.com/jenkins/job/AnotherJob/",
"color": "disabled"
},
{
"name": "AnotherJob2",
"url": "https://build.example.com/jenkins/job/Build%20CI%20Build/",
"color": "blue"
}
],
"views": [
{
"name": "-All Views",
"url": "https://build.example.com/jenkins/view/-All%Views/"
},
{
"name": "Alle",
"url": "https://build.example.com/jenkins/"
}
]
}

How to deserialize this json with Gson?

I am going to deserialize this json string with Gson
{
"ads": [
{
"ad": {
"id": 1,
"title": "...",
"publicImage": "...",
"publicUrl": "...",
"adposition": {
"name": "home"
},
"ttl": 30,
"debug": false
}
},
{
"ad": {
"id": 2,
"title": "...",
"publicImage": "...",
"publicUrl": "...",
"adposition": {
"name": "splash"
},
"ttl": 30,
"debug": false
}
},
{
"ad": {
"id": 3,
"title": "...",
"publicImage": "...",
"publicUrl": "...",
"adposition": {
"name": "home"
},
"ttl": 30,
"debug": false
}
}
],
"message": "issue list generated",
"status": "success"
}
and what I have create for classes is (getter setter has been removed) :
public class Ad {
public class AdPosition{
private String mName;
public String getName() {
return mName;
}
public void setName(String name) {
mName = name;
}
}
#SerializedName("id")
private int mID;
#SerializedName("title")
private String mTitle;
#SerializedName("publicImage")
private String mPublicImage;
#SerializedName("publicUrl")
private String mPublicUrl;
#SerializedName("ttl")
private int mTtl;
#SerializedName("adposition")
private AdPosition mAdPosition;
}
and
public class AdsListResponse {
#SerializedName("ads")
private List<Ad> mAds;
#SerializedName("message")
private String mMessage;
#SerializedName("status")
private String mStatus;
}
and for converting I use below code
Gson gson = new GsonBuilder().setPrettyPrinting().create();
AdsListResponse ads = gson.fromJson(response, AdsListResponse.class);
for(Ad ad : ads.getAds()){
if(ad.getAdPosition().getName().equalsIgnoreCase("splash")){
System.out.println(ad.getAdPosition().getName());
}
But my list contains objects(Ad) but every field of them is null, for example it has 3 ad but id,title,... are all null, what should I do?
Sorry I copied and paste it wrongly, but still the problem is there, my list of Ad contains Ad but each field of Ad is null
Let's analyze your JSON
{ // an object at the root
"ads": [ // a key value pair, where the value is an array
{ // an object within the array
"ad": { // a key value pair, where the value is an object
// bunch of key value pairs, with int, string, boolean or object values
"id": 1,
"title": "...",
"publicImage": "...",
"publicUrl": "...",
"adposition": {
"name": "home"
},
"ttl": 30,
"debug": false
}
},
Considering that a JSON object maps to a Java POJO, a JSON string maps to a Java String, a JSON array maps to a Java array or Collection, and keys maps to fields, let's analyze your POJO classes
public class AdsListResponse { // root is an object
#SerializedName("ads")
private List<Ad> mAds; // field of type List (Collection) mapping to the array
So you've mapped
{ // an object at the root
"ads": [ // a key value pair, where the value is an array
{
The next token is
"ad": { // a key value pair, where the value is an object
You have no POJO where this exists. You'd need something like
public class AdWrapper {
#SerializedName("ad")
private Ad mAd;
and then change the AdsListResponse to
class AdsListResponse {
#SerializedName("ads")
private List<AdWrapper> mAds;
}
to complete the object tree.

Gson; list of objects in list of objects

I have json which looks like this:
[{
"id":14,
"namelanguage1":"Książka",
"namelanguage2":"das Buch",
"tags":
[{
"id":2,
"name":"Szkoła",
"language_user_id":null,
"created_at":"2014-04-11T17:30:28.356Z",
"updated_at":"2014-04-11T17:30:28.356Z",
"user_id":2
}],
"language1_id":5,
"language2_id":1,
},
{
"id":15,
"namelanguage1":"das Fußball",
"namelanguage2":"Piłka nożna",
"tags":[{
"id":2,
"name":"Szkoła",
"language_user_id":null,
"created_at":"2014-04-11T17:30:28.356Z",
"updated_at":"2014-04-11T17:30:28.356Z",
"user_id":2
},
{
"id":3,
"name":"Sport",
"language_user_id":null,
"created_at":"2014-04-11T17:30:33.059Z",
"updated_at":"2014-04-11T17:30:36.769Z",
"user_id":2
}],
"language1_id":1,
"language2_id":5,
}]
I don't know how to get a tag id. Now I have this:
public class Word {
#SerializedName("id")
public long id;
#SerializedName("namelanguage1")
public String nameLanguage1;
#SerializedName("namelanguage2")
public String nameLanguage2;
#SerializedName("language1_id")
public long language1_id;
#SerializedName("language2_id")
public long language2_id;
public ArrayList<Tag> tags;
and getters and setters for it. I don't know how to get id of tags. I try understand this example: example from stackoverflow but still I don't know how to do this.
It's how i have it in code:
words = VolleyDemoApplication.obtain().getGson()
.fromJson(response, new TypeToken<ArrayList<Word>>() {
}.getType());
I get values from word like this:
word.getNameLanguage1() + " " +word.getLanguage1_id() + " " + word.getNameLanguage2()+ " " + word.getLanguage2_id() + " " + word.getTags().
And here word.getTags(). and I don't know what write then.
There are a couple of things to point out, i have no clue why this code worked for you, when the json you have printed is not correct.
The actual format is :
[
{
"id": 14,
"namelanguage1": "aaa",
"namelanguage2": "das Buch",
"tags": [
{
"id": 2,
"name": "bbb",
"language_user_id": null,
"created_at": "2014-04-11T17:30:28.356Z",
"updated_at": "2014-04-11T17:30:28.356Z",
"user_id": 2
}
],
"language1_id": 5,
"language2_id": 1 ->> remove the comma here thats in your json text
},
{
"id": 15,
"namelanguage1": "zzz",
"namelanguage2": "yyy",
"tags": [
{
"id": 2,
"name": "ccc",
"language_user_id": null,
"created_at": "2014-04-11T17:30:28.356Z",
"updated_at": "2014-04-11T17:30:28.356Z",
"user_id": 2
},
{
"id": 3,
"name": "Sport",
"language_user_id": null,
"created_at": "2014-04-11T17:30:33.059Z",
"updated_at": "2014-04-11T17:30:36.769Z",
"user_id": 2
}
],
"language1_id": 1,
"language2_id": 5 ->> remopve the comma here too
}
]
The class word will need a SerializedName for tags arraylist.
#SerializedName(value="tags")
public ArrayList<Tag> tags;
You will need to create the tags class too:
public class Tag {
#SerializedName(value="id")
private int id;
#SerializedName(value="name")
private String tagName;
#SerializedName(value="language_user_id")
private String languageUserId;
#SerializedName(value="created_at")
private String createdAt;
#SerializedName(value="updated_at")
private String updatedAt;
#SerializedName(value="user_id")
private int userId;
// create getters and setters or else change the modifiers to public
}
You will access id in Tag class like this:
words.get(0).tags.get(0).getId(); ->> i am using 0 since its the first element, you will need a loop for this
or
words.get(0).tags.get(0).id;
Hope that helps.

Categories