How to parse this Json-String with Gson? - android

I want to parse a Json string from a web-api. Here is it:
{
"RANDOM_ID": {
"lnk_typ": "pdf",
"lnk_description": "Description 1",
"lnk_link": "https://example.com",
"direktdownload": "https://example.com/download1"
},
"RANDOM_ID": {
"lnk_typ": "lnk",
"lnk_description": "Description 2",
"lnk_link": "https://example.com",
"direktdownload": "https://example.com/download2"
}
}
Now my problem:
RANDOM_ID could be every positive number, so it could be 230 or 5 (or
every other positive number).
Also the number of objects can change, i
mean there could more than just 2 RANDOM_ID-Objects.
And i want to know, how to parse this Json. I prefer to do this with Gson, but it could be parsed manual too, if there is a way to do this.

You need to have a class that represent your json string
You can do it manually or generate it with : http://www.jsonschema2pojo.org/ ( set your package name, a class name, choose json as source type and gson as annotation style )
Then you can get item from object like this :
MyObject.getLnkTyp();

Related

How to parse the different type of json

When I call an api with specific parameter, I get a json like this:
{
“name”:“my name”,
“family”:”my family”
},
{
“name”:“my name1”,
“family”:”my family1”
}
But when I call same api with different parameter I get same JSON but with the different type for example an empty array :
[]
How can create a data model for this type of response in kotlin?

JsonArray as empty string parsing issue with retrofit

I have a json in which 1 key is coming as jsonArray if it has data otherwise it is coming as empty string. It is giving error while parsing in gson with retrofit.
"section": "Technology",
"subsection": "",
"title": "Depiction of Amazon Stirs a Debate About Work Culture",
"abstract": "Details of working conditions at Amazon led to a response from employees, relatives and friends.",
"url": "http://www.nytimes.com/2015/08/19/technology/amazon-workplace-reactions-comments.html",
"byline": "By THE NEW YORK TIMES",
"item_type": "Article",
"updated_date": "2015-08-18T07:35:33-5:00",
"created_date": "2015-08-18T07:35:35-5:00",
"published_date": "2015-08-19T04:00:00-5:00",
"material_type_facet": "News",
"kicker": "",
"des_facet": [
"Workplace Environment"
],
"org_facet": [
"Amazon.com Inc"
],
"per_facet": "",
"geo_facet": "",
des_facet , org_facet, per_facet, geo_facet are jsonArray but you can see that 2 are not having data so coming as empty string.
How to handle this scenario with retrofit +gson.
Json format can't be changed here at server.
is there any way I can achieve it in android?
Ok so there are two option you can solve this
Option 1:
JSON which I used as a example
"des_facet": [
"Workplace Environment"
],
"org_facet": [
"Amazon.com Inc"
],
"per_facet": ["Akshay"],
"geo_facet": ""
In your model class convert those variable to Object type
#Expose
#SerializedName("geo_facet")
private Object geo_facet;
#Expose
#SerializedName("per_facet")
private Object per_facet;
then where you want to set data do the following
if (model != null)
{
if (model.getGeo_facet() != null || model.getGeo_facet() != "")
{
Object arr = model.getGeo_facet();
}
if (model.getPer_facet() !=null || model.getPer_facet()!= "")
{
Object arr = model.getPer_facet();
if (arr!=null && arr.toString().length()>0)
{
arr = arr.toString();
Log.d("akshay","arr= "+arr);
//Do your Stuff or Set data
}
}
}
This is the output= 08-11 16:51:29.830 17951-17951/com.android.example
D/akshay: arr= [Akshay]
Option 2:
Follow this which is a little bit complex
Option 3:
Write own custom Parsing like this and Handle your response accordingly
a json can have a single structure. From the code it is clear that the key is given with 2 types of data
Ideally, it should not give "" when no items. It should give null
Please change the data
If no items,
"des_facet"=null // this is the change on server side. No need to change it on app side
If it has items
"des_facet"=[
"Workplace Environment"
]
instead of
If no items,
"des_facet"=""
If it has items
"des_facet"=[
"Workplace Environment"
]
You can use AutoValue with gson plugin and mark the field as nullable which will notify the Autovalue to make this field optional.
AZs an example this is how you do it:
#AutoValue
public abstract class NewsResponse{
public static TypeAdapter<NewsResponse> typeAdapter(Gson gson){
return new AutoValue_NewsResponse.GsonTypeAdapter(gson);
}
#SerializedName("api_status")
public abstract String apiStatus();
#SerializedName("api_text")
public abstract String success();
#Nullable
#SerializedName("errors")
public abstract ErrorDetails errorDetails();
#SerializedName("news")
public abstract List<NewsDetails> newsDetails();
}
you must import both of them see more info about importing at: AutoValue and AutoValue Gson Plugin

DeSerializing dynamic array in GSON

I am working on JSON response . I want to store JSON response in model then store the model values into DB.
So that I used GSON to parse the JSON response.
In my response I have some dynamic JSON array names. The sample and part of the response is below.
{
"TD": [
{
"TimeClockDetails": {
"March 2, 2016": [
{
"TimeclockId": "148148",
},
]
}
In that response , I have the ""March 2, 2016":" array . If a static array name means I can use #SerializeName("arrayname_in_response").
Now, how can I deserialize this dynamic array name ?
If need more clarification,I am ready to provide.
One solution would be to use a Map.
#SerializedName("TimeClockDetails")
private Map<String, TimeDetail> mTimeClockDetails;
This way the date keys would end as keys in the map.

How to parse such type of JSON data for the dynamic key

{"Freedom Plan 4900":
{
"sale_price1":["$10.00","$20.00","$25.00","$50.00","$100.00"],
"loc_rate1":["India (2.0¢ per min)"],
"net_minutes1":["500","1,000","1,250","2,500","5,000"],
"loc_rate":["India - Mobile (1.5¢ per min)"],
"net_minutes":["666","1,333","1,666","3,433","6,866"]
},
"Super Offer Plan":
{
"sale_price1":["$10.00"],
"loc_rate1":["India (1.5¢ per min)"],
"net_minutes1":["667"],
"loc_rate":["India - Mobile (1.0¢ per min)"],
"net_minutes":["1,000"]
}
}
i want to parse this json string
I would use something like GSON:
http://sites.google.com/site/gson/gson-user-guide
Create classes to hold the data (e.g. PhonePlan etc) and let GSON parse the JSON string.
PhonePlan plan = gson.fromJson(json, PhonePlan.class);

How to get a JSON with dollar sign

suppose I have {"data": {"243232": {"id": "testid","name": "test" } }}
so how to get correct value thanks.
you cant directly pass above String with Gson as "243232" is number and we cant declare variable which start from number, So for parsing this you must modify the string with some notification
i.e. {"data": {"temp243232": {"id": "testid","name": "test" } }}
here i modified string manually "243232" by "temp243232", now you can parse it
You can use a JSON parser for Java like Google GSON. This works best if the class whose object your data in json represents, is known to you.
String str = ""; //contains your json string
Gson gson = new Gson();
MyClass var = gson.fromJson(str,MyClass.class);
where MyClass will be a class which represents the object.
Then you can access data just like you'd do from a data structure in your program, it'll be something like var.data.

Categories

Resources