Using Gson on Android, how should I set my Java classes to parse a JSON like this (from Sickbeard API):
{
"data": {
"1": {
"airdate": "2011-09-04",
"name": "Something Wicked This Fae Comes",
"quality": "HD TV",
"status": "Downloaded"
},
"2": {
"airdate": "2011-09-11",
"name": "I Fought the Fae (And the Fae Won)",
"quality": "N/A",
"status": "Wanted"
},
"3": {
"airdate": "2011-09-18",
"name": "Scream a Little Dream",
"quality": "N/A",
"status": "Unaired"
},
"4": {
"airdate": "2011-09-25",
"name": "Episode 4",
"quality": "N/A",
"status": "Unaired"
},
"5": {
"airdate": "",
"name": "Episode 5",
"quality": "N/A",
"status": "Skipped"
}
},
"message": "",
"result": "success"
}
These "1", "2", etc could be a number from 0 to whatever (and it may even be a "specials").
Your classes should look like this
class Response
#Expose #SerializedName("data")
private HashMap<Integer, DataObject> dataList;
#Expose #SerializedName("message")
private String message;
#Expose #SerializedName("result")
private String result;
class DataObject
#Expose #SerializedName("airdate")
private String airdate;
#Expose #SerializedName("name")
private String name;
... //other objects
And getter and setter and so on, now you should be able to parse it. But if you have the possibility to change the api I would suggest you to change the data List to a real json List of objects!!
Related
This question already has answers here:
How do I parse JSON in Android? [duplicate]
(3 answers)
how to parse JSONArray in android
(3 answers)
How to Parse json response using Gson Library in android?
(4 answers)
Closed 1 year ago.
[
[
{
"description": "",
"product": "Apple",
"quantity": "2"
},
{
"description": "",
"product": "Apple",
"quantity": "2"
},
{
"description": "",
"product": "Apple",
"quantity": "2"
}
],
[
{
"description": "",
"product": "banana",
"quantity": "1"
},
{
"description": "",
"product": "banana",
"quantity": "1"
},
{
"description": "",
"product": "banana",
"quantity": "1"
}
]
]
This is my class
public class items_list{
private String product;
private String quantity;
private String description;
public items_list(String product, String quantity, String description) {
this.product = product;
this.quantity = quantity;
this.description = description;
}
}
This is how my ArrayList look like
ArrayList<ArrayList<items_list>> list = new ArrayList<>();
I am a developing an android app to save a arraylist of object, and I want to store an arraylist of arraylist of object. I have no problem converting it into json file using gson, but I am having difficulty converting it back.
Pointers would be appreciated:)
I'm trying to parse this json bellow, into a object named AlbumResponse that have another two objects inside, Album and PaginationInfo. Retrofit version 2.0
[
{
"id": "6",
"name": "King Stays King",
"artist_name":"Timbaland",
"image":""
},
{
"id": "7",
"name": "East Atlanta Santa 2",
"artist_name":"Gucci Mane",
"image":""
},
{
"id": "8",
"name": "The cuban connect",
"artist_name":"Phophit",
"image":""
},
{
"id": "9",
"name": "Shmoney Keeps",
"artist_name":"Calling",
"image":""
},
{
"id": "10",
"name": "Cabin Fever 3",
"artist_name":"Wiz khalifa",
"image":""
}
],
{
"nextPage": "http://private-ede172-mymixtapez1.apiary-mock.com/features/page_3/",
"itemsTotal": 10,
"page": 2,
"pagerMax": 2
}
Album class
public class Album {
long id;
String name;
#SerializedName("artist_name")
String artistName;
String image;
}
PaginationInfo class
public class PaginationInfo {
int page;
int pagerMax;
int nextPage;
int itemsTotal;
}
AlbumResponse, that have both classes above inside, and Album is a List
public class AlbumResponse {
public List<Album> albums;
public PaginationInfo paginationInfo;
}
The request
Call<AlbumResponse> responseCall = albumService.features();
responseCall.enqueue(new Callback<AlbumResponse>() {
#Override
public void onResponse(Response<AlbumResponse> response, Retrofit retrofit) {
if(response.isSuccess()) {
AlbumResponse albumResponse = response.body();
PaginationInfo paginationInfo = albumResponse.getPaginationInfo();
}
System.out.println();
}
#Override
public void onFailure(Throwable t) {
System.out.println(t.getMessage());
}
});
Interface
public interface AlbumService {
#GET("/features/")
Call<AlbumResponse> features();
}
The problem is that im getting a Throwable that contains:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $`
Please, can someone help me, i not found any answers in stackoverflow. Thanks.
The error says: the Parser expected a JSON-Object but it reads a JSON-array. To fix it (if you control the server) you should change the JSON String to something like this:
{
"albums" : [
{
"id": "6",
"name": "King Stays King",
"artist_name":"Timbaland",
"image":""
},
{
"id": "7",
"name": "East Atlanta Santa 2",
"artist_name":"Gucci Mane",
"image":""
},
{
"id": "8",
"name": "The cuban connect",
"artist_name":"Phophit",
"image":""
},
{
"id": "9",
"name": "Shmoney Keeps",
"artist_name":"Calling",
"image":""
},
{
"id": "10",
"name": "Cabin Fever 3",
"artist_name":"Wiz khalifa",
"image":""
}
],
"paginationInfo" : {
"nextPage": "http://private-ede172-mymixtapez1.apiary-mock.com/features/page_3/",
"itemsTotal": 10,
"page": 2,
"pagerMax": 2
}
}
Now it's a JSON-Object and is conform to your Java class.
If you cannot change the JSON on the backend, I would take it as row response and parse the albums Array and the PaginationInfo separately using GSON or manually.
Btw. you must change the nextPage type from int to String in the PaginationInfo class
Your JSON have a trouble in initial declaration.
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.
Try update your JSON to:
"albums": [
{
"id": "6",
"name": "King Stays King",
"artist_name":"Timbaland",
"image":""
},
{
"id": "7",
"name": "East Atlanta Santa 2",
"artist_name":"Gucci Mane",
"image":""
},
{
"id": "8",
"name": "The cuban connect",
"artist_name":"Phophit",
"image":""
},
{
"id": "9",
"name": "Shmoney Keeps",
"artist_name":"Calling",
"image":""
},
{
"id": "10",
"name": "Cabin Fever 3",
"artist_name":"Wiz khalifa",
"image":""
}
],
"pagination_info":
{
"nextPage": "http://private-ede172-mymixtapez1.apiary-mock.com/features/page_3/",
"itemsTotal": 10,
"page": 2,
"pagerMax": 2
}
I wanna create some Objects in my Realm using "realm.createOrUpdateAllFromJson(type.class, json-array)". But it throws error -> could not map json.
Heres the Json-Array. It's valid.
[
{
"uuid": "99975b79-adac-4baa-a1ab-96c0db23c0ee",
"name": "Joris"
},
{
"uuid": "0",
"name": "Adrian"
},
{
"uuid": "0",
"name": "Oliver"
},
{
"uuid": "0",
"name": "Michael"
},
{
"uuid": "0",
"name": "David"
},
{
"uuid": "0",
"name": "Daniel"
}
]
and heres my Owner-Model.
public class Owner extends RealmObject{
#PrimaryKey
private String uuid; //PK
private String name;
private String token;
private RealmList<Idea> ideas;
private RealmList<Vote> votes;
Here's the code where the error is thrown. its in the 3. line
realm.beginTransaction();
realm.createOrUpdateAllFromJson(Tag.class, tagJson);
realm.createOrUpdateAllFromJson(Owner.class, ownerJson);
realm.commitTransaction();
it's strange how the creating of Tag-Objects works fine..
please help!!
greetings john
You UUID is marked as a #PrimaryKey and you have multiple "uuid"'s with the value 0. This means that you are breaking the primary key constraint of only having one element with each uuid. If you look closely in LogCat you will probably see that Could not map JSON exception mentions this as well.
I am using volley in my app for network requests.I am trying to use GSON library for JSON parsing and create a list view with that.JSON looks like this.When I try to run the code I got an exception. What is wrong with this and what is missing
[
{
"articles": {
"code": "/par/feed_sub_section",
"name": "News",
"title": "News",
"count": "25",
"page": "1",
"totalPages": "11",
"expiryTime": 100
},
"article": [
{
"title": "title 1",
"articleUrl": "articleUrl 1",
"thumbnail": "thumbnail 1",
"imgWeb": "imgWeb 1",
"imgMob": "imgMob 1",
"lastModified": "lastModified1",
"otherImages": "0",
"video": "false"
},
{
"title": "title2",
"articleUrl": "articleUrl2",
"thumbnail": "thumbnail2",
"imgWeb": "imgWeb2",
"imgMob": "imgMob2",
"lastModified": "lastModified2",
"otherImages": "0",
"video": "false"
},
{
"title": "title3",
"articleUrl": "articleUrl3",
"thumbnail": "thumbnail3",
"imgWeb": "imgWeb3",
"imgMob": "imgMob3",
"lastModified": "lastModified3",
"otherImages": "0",
"video": "false"
},
{
"title": "title4",
"articleUrl": "articleUrl4",
"thumbnail": "thumbnail4",
"imgWeb": "imgWeb4",
"imgMob": "imgMob4",
"lastModified": "lastModified4",
"otherImages": "0",
"video": "false"
}
]
}]
and my classes is like
public class Article {
String title;
String articleUrl;
String thumbnail;
String imgWeb;
String imgMob;
String lastModified;
String otherImages;
String video;}
public class Articles {
String code;
String name;
String title;
String count;
String page;
public class ArticleMainObject {
public Articles articles;
public List<Article> articleList;}
I use volley and try to parse result like this
GsonRequest<ArticleMainObject> myReq = new GsonRequest<ArticleMainObject >(Method.GET,
"http://JSONURL/",
ArticleMainObject .class,
createMyReqSuccessListener(),
createMyReqErrorListener());
When i run this code i got exception like this
com.android.volley.ParseError: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 4 column 2
I am stuck at this point.How to iterate through the result.I am new to GSON.So please help me
Have been scratching my head on this one. The JSON Response is a valid one:
{
"MRData": {
"xmlns": "http://ergast.com/mrd/1.4",
"series": "f1",
"url": "http://ergast.com/api/f1/current/2.json",
"limit": "30",
"offset": "0",
"total": "1",
"RaceTable": {
"season": "2014",
"round": "2",
"Races": [
{
"season": "2014",
"round": "2",
"url": "https://en.wikipedia.org/wiki/2014_Malaysian_Grand_Prix",
"raceName": "Malaysian Grand Prix",
"Circuit": {
"circuitId": "sepang",
"url": "http://en.wikipedia.org/wiki/Sepang_International_Circuit",
"circuitName": "Sepang International Circuit",
"Location": {
"lat": "2.76083",
"long": "101.738",
"locality": "Kuala Lumpur",
"country": "Malaysia"
}
},
"date": "2014-03-30",
"time": "08:00:00Z"
}
]
}
}
}
The POJO for the response:
public class ApiResponse {
MRData mrdata;
public class MRData {
String xmlns;
String series;
String url;
String limit;
String offset;
String total;
RaceTable raceTable;
}
}
The apiResponse object is always null. Anyone can point out what is wrong with the POJO object here?
Thanks.
I see a couple of potential issues here:
You are defining a class inside another class; I have never seen it done like this. You might want to separate in two different files.
Your variable names on your POJO should match the variable names on the JSON response exactly. For example:
public class ApiResponse {MRData MRData;}
If you want your POJO's variables to be different than what the JSON sends back, you should use #SerlizedName.