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
Related
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.
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!!
I want to get the name of school from this type of json :
"username": "blah",
"education": [
{
"school": {
"id": "[removed]",
"name": "[removed]"
},
"year": {
"id": "[removed]",
"name": "[removed]"
},
"type": "High School"
},
{
"school": {
"id": "[removed]",
"name": "[removed]"
},
"year": {
"id": "[removed]",
"name": "[removed]"
},
"type": "College"
}
]
here is my code :
JSONObject obj=null;
URL img_url;
String jsonUser = facebook.request("me");
obj=Util.parseJson(jsonUser);
String id=obj.optString("id");
String name=obj.optString("name");
what should i write the code to get the education fields school name ?
Facebook fb = new Facebook(API_KEY);// ... login user here ...JSONObject me = new JSONObject(fb.request("me")); String id = me.getString("id");
you can try
var schoolname = yourobject.education.school.name
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"));