Trouble retrieving data from web service using GSON - android

I have tried a lot of samples and tutorials about GSON and how things would work using it such as:
http://www.softwarepassion.com/android-series-parsing-json-data-with-gson/
http://androidsmith.com/2011/07/using-gson-to-parse-json-on-android/
and etc.
My problem is that I have this json value returned by my http://localhost:3000/users/1.json, which is:
{
"created_at": "2012-09-20T01:43:15Z",
"id": 1,
"name": "kevin",
"updated_at": "2012-09-20T01:43:15Z"
}
Another is in this url http://localhost:3000/users.json which has a json value
[ {
"created_at": "2012-09-20T01:43:15Z",
"id": 1,
"name": "kevin",
"updated_at": "2012-09-20T01:43:15Z"
}, {
"created_at": "2012-09-20T01:43:33Z",
"id": 2,
"name": "pineda",
"updated_at": "2012-09-20T01:43:33Z"
}, {
"created_at": "2012-09-20T01:46:08Z",
"id": 3,
"name": "raphael",
"updated_at": "2012-09-20T01:46:08Z"
}, {
"created_at": "2012-09-20T16:13:42Z",
"id": 4,
"name": null,
"updated_at": "2012-09-20T16:13:42Z"
}, {
"created_at": "2012-09-20T16:18:03Z",
"id": 5,
"name": null,
"updated_at": "2012-09-20T16:18:03Z"
}, {
"created_at": "2012-09-20T16:19:23Z",
"id": 6,
"name": null,
"updated_at": "2012-09-20T16:19:23Z"
}, {
"created_at": "2012-09-20T16:20:41Z",
"id": 7,
"name": null,
"updated_at": "2012-09-20T16:20:41Z"
}
]
I am having a bit of a hard time parsing such data and getting it for storage purposes.

In order to parse your JSON, you first need to create a class to wrap your data. In your case:
public class Item {
#SerializedName("created_at")
private String createdAt;
#SerializedName("id")
private int id;
#SerializedName("name")
private String name;
#SerializedName("updated_at")
private String updatedAt;
//getters and setters
}
Then, in order to parse your 1st JSON reponse, you just have to do:
Gson gson = new Gson();
Item item = gson.fromJson(your1stJsonString, Item.class);
Your 2nd JSON response is a bit more tricky, because it's an array. The problem is that you can't simply do:
List<Item> item = gson.fromJson(your1stJsonString, List<Item>.class); //wrong!
The previous code fails because Java can't know the class of List<Item> due to type erasure.
So you have to do it this way:
Type itemListType = new TypeToken<List<Item>>() {}.getType();
List<User> itemList = gson.fromJson(your2stJsonString, itemListType);
And that's all, once you have parsed your JSON response in your object (or list of objects) you can access all the retrieved data as usual:
String name = itemList.get(i).getName();
Note 1: Notice that I've set the types of attributes created_at and updated_at as just String, because it makes things easier. I usually do it this way, and then I parse the Date or any other confictive type. Anyway, if you want to directly parse the dates, I think you can use a Custom Deserializer following Gson's User Guide.
Note2: The use of the annotation #SerializedName is interesting to separate the name of a field in the JSON response and in your app, in order to follow Java naming conventions...

Related

How to remove extra json object in flutter

This is my cart list and I'm converting into JSON object to send at the server
Map<String,dynamic> str={'cart':cartList};
cartitem = jsonEncode(str);
doing something like this but it is adding extra JSON object and this is invalid JSON form. then how can I remove extra JSON object.
{
{"cart":[
{
"cartid":2,
"pid":"342702",
"merchantId":"MER-07156",
"hashkey":"7087fea71afc963d6dc3fa04944008ec",
"productname":"Scheduling Product - Edit Please",
"product_image":"Scheduling Product - Edit Please",
"shipping_price":"0.00",
"state_tax_rate":"0.0",
"taxamt":"0.00",
"discountamt":"0.0",
"price":"10.00",
"pricewithattr":"17.00",
"quantity":"18",
"totalamount":"306.00",
"taxvalue":"0.0",
"attribute_array":"[{\"attributeid\":\"20796\",\"attributename\":\"Black\",\"groupname\":\"Color\",\"groupid\":\"3012\"},{\"attributeid\":\"20798\",\"attributename\":\"Silk\",\"groupname\":\"Cloth\",\"groupid\":\"3013\"},{\"attributeid\":\"20800\",\"attributename\":\"small\",\"groupname\":\"Size\",\"groupid\":\"3014\"}]",
"is_free":"0",
"is_payable_later":"0",
"isattrpresent":"1"
}
]
}}
Strange, because this code:
Map<String, dynamic> str = {
'cart': [1, 2, 3]
};
String cartitem = jsonEncode(str);
print(cartitem);
which does basically the same thing, produces valid json:
{"cart":[1,2,3]}
Try debugging by just json encoding one of the cart members, replacing the cart members by something simple (like an integer, above) until you find the issue.
Your JSON is not right structure.
Did you try to parse it any online converter?
You should remove { character before "cart" and remove } character the end of json.
I tried to debug and found that jsonEncode was adding an extra object so I converted cartiem into jsonEncode prior to adding into the map.
var cartitems2=cartList;
Map<String,dynamic> str={'"cart"':json.encode(cartitems2)};
cartitem = str.toString();
debugPrint('CART :-----${cartitem}');
Expected Result
{
"cart": [
{
"cartid": 22,
"pid": "342702",
"merchantId": "MER-07156",
"hashkey": "7087fea71afc963d6dc3fa04944008ec",
"productname": "Scheduling Product - Edit Please",
"product_image": "Scheduling Product - Edit Please",
"shipping_price": "0.00",
"state_tax_rate": "0.0",
"taxamt": "0.00",
"discountamt": "0.0",
"price": "10.00",
"pricewithattr": "26.00",
"quantity": "10",
"totalamount": "260.00",
"taxvalue": "0.0",
"attribute_array": [
{
"attributeid": "20794",
"attributename": "Red",
"groupname": "Color",
"groupid": "3012"
},
{
"attributeid": "20799",
"attributename": "Cotton",
"groupname": "Cloth",
"groupid": "3013"
},
{
"attributeid": "20800",
"attributename": "small",
"groupname": "Size",
"groupid": "3014"
}
],
"is_free": "0",
"is_payable_later": "0",
"isattrpresent": "1"
}
]
}

Response object value comes in array and some time object , how identify in my code?

My response have many values, but one is filter object that are coming some time in array nad some time in object.
How to find this one is object or array, i am using Gson in android.
Comming in array like this,
"filter": [
{
"id": 3,
"level": "0",
"parent_id": 0,
"category_name": "Women",
"LEVEL1": [
{
"id": 130,
"level": "1",
"parent_id": 3,
"parent_name": "Women",
"category_name": "Saree",
"LEVEL2": [
{
"id": 152,
"level": "2",
"parent_id": 130,
"parent_name": "Saree",
"parent_parent_id": 3,
"parent_parent_name": "Women",
"category_name": "Party Wear"
}
]
}
]
Some time coming like this,
"filter": {
"0": {
"attribute_title": "Brand",
"attribute_id": 1,
"childs": [
{
"child_attribute_name": "Ambica",
"child_attribute_id": 530,
"count": 38
}
]
}
I am using Gson then how to identify in code,
Using GSON API :
Create JsonObject from response json and pass it to following method :
public Class<?> getJSONType(JsonObject jsObj) {
GsonBuilder gBuilder = new GsonBuilder();
Gson gson = gBuilder.create();
Object obj = gson.fromJson(jsObj.get("filter"), Object.class);
if(obj instanceof List){
return List.class;
}else if(obj instanceof Map){
return Map.class;
}
return null;
}
Here I have considered that filter is top level element in your JSON.
The code jsObj.get("filter") should be modified to reach up to correct location.

android - Retrofit 2:Correct way of Parsing JSON with multiple arrays

I have started using retrofit:2.0.2 first time into my new project and I have done with first service call using retrofit but am not sure is it correct way or not here is what i have done
web services response
{
"status": true,
"message": "",
"data": {
"schools": [ { "id": "1", "name": "test 1" }, { "id": "2", "name": "test 12" }],
"referrals": [ { "id": "195", "name": "test 1" }, { "id": "1483", "name": "test 12" }],
"Brands": [ { "id": "195", "name": "test 1" }, { "id": "1483", "name": "test 12" }],
"Teams": [ { "id": "195", "name": "test 1" }, { "id": "1483", "name": "test 12" }],
"positions": [ { "id": "195", "name": "test 1" }, { "id": "1483", "name": "test 12" }],
}
}
created 3 model classes to map above response
public class SimpleObject {
int id;
String name;
// getter setter
}
public class SimpleData {
private List<SimpleObject> schools = new ArrayList<SimpleObject>();
private List<SimpleObject> referrals = new ArrayList<SimpleObject>();
private List<SimpleObject> positions = new ArrayList<SimpleObject>();
private List<SimpleObject> Teams = new ArrayList<SimpleObject>();
private List<SimpleObject> Brands = new ArrayList<SimpleObject>();
// getter, setter
}
public class ResponseData{
boolean status;
String message;
SimpleData data;
// getter setter
}
and then made a service call using Retrofit2
call.enqueue( new Callback<ResponseData>() {
#Override
public void onResponse(Call<ResponseData> call, Response<ResponseData> response) {
}
#Override
public void onFailure(Call<ResponseData> call, Throwable t) {
}
and its working fine but a want to insure that is it best way of doing this or can any one suggest the best way of handling such a response without creating multiple model classes for simple data (there should me only one model class "SimpleObject" and other will be list of "SimpleObject")
Please comment or suggest best way to handling response thanks.
The way you currently have it structured looks correct. You need to have one model for every nested level in the JSON response, which you have.
The only other option is simply breaking the object up using keys to pull all of the JSONObjects and JSONArrays, which I do not recommend.
copy and paste your json response in the link given below and download zip file and put it in your project directly.
This link will convert your any kind of json response and convert it into POJO

Retrofit POJO is null but JSON is valid

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.

Store Json from httpResponse into Android SQLite Database

How can I easily store this large amount of data into A SQLite database?
I read that I could use Gson to parse this data, but I'm not exactly sure how to do that.
I already have created a SQLiteHelper and the necessary classes, I am just stuck on how to parse this data.
I am getting a httpResponse that returns a large amount of Json that looks like this:
"objs": {
"ptoStatus": [
{
"id": 1,
"modifieddate": "2006-07-06 05:35:38",
"description": "Submitted",
"name": "Submitted",
"createddate": "2007-07-06 09:43:38"
},
{
"id": 2,
"modifieddate": "2006-07-06 09:35:38",
"description": "Approved",
"name": "Approved",
"createddate": "2009-07-06 09:35:38"
},
{
"id": 3,
"modifieddate": "2009-07-06 09:50:38",
"description": "Denied",
"name": "Denied",
"createddate": "2009-07-06 09:35:38"
}
],
"alertStates": [
{
"id": 1,
"createddate": "2008-02-11 09:11:57",
"modifieddate": "2008-02-11 09:11:57",
"description": "Sending"
},
{
"id": 2,
"createddate": "2008-02-11 09:11:57",
"modifieddate": "2008-02-11 09:11:57",
"description": "Response"
},
{
"id": 3,
"createddate": "2008-02-11 09:11:57",
"modifieddate": "2008-02-11 09:11:57",
"description": "Acknowledge"
},
//etc....
Retrofit is a great REST client for android applications. Here you can find the documentation:
http://square.github.io/retrofit/
You can use it for getting the http responses, but with it you can just turn all your response data into Java objects (by default it uses Googles Gson parser for that)
For that particular json you need to create something like this:
public class ObjsResponse {
public MyObjects data;
public class MyObjects {
List<States> ptoStatus;
List<AlertStates> alertStates;
}
}
And the models you store in the database just need to have the same names (or you can use annotations for different keys in the json, but that is all documented at Gson), like this:
public class States {
int id;
String modifieddate; //here you can use some sort of DateTime too (for example jodatime)
String description;
String name;
String createddate;
}
And here you can use the database annotations or anything you like.
After this you just have to set this ObjsResponse class as the return param to the retrofit interface (described at the upper link), have it initialized, then you can call this method. I don't write down the hole thing, in the documentation's Introduction section is basically all you need ;)

Categories

Resources