Store Json from httpResponse into Android SQLite Database - android

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 ;)

Related

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

Deserializing different objects in JSON array (GSON)

The JSON result for getUsers I get from the server looks like this:
{
"result": [
{
"meta": {
"rows": "3"
}
},
{
"items": [
{
"id": "1",
"name": "Steve",
"age": "30"
},
{
"id": "2",
"name": "Mary",
"age": "29"
},
{
"id": "3",
"name": "Bill",
"age": "58"
}
]
}
]
}
How can I deserialize it by GSON in my android app (I'm using retrofit)?
I can't imagine any wrapper classes because of the different object types in result.
Any help would be appreciated!
For good example
Converting JSON to Java
Other way, you can convert your json to a java object
Please use org.json library http://www.json.org/java/index.html
Then, for example
json = new JSONObject(YOUR_JSON).getJSONObject("result");
JSONArray items = data.getJSONArray("items");
String name = items.getJSONObject(0).getString("name");
You can write a TypeAdapter for a type that will be (de)serialized to(from) array. You can even make it generic, so it will work with type like Pair<A, B>. Here is an example for non-generic type: https://github.com/cakoose/json-tuple-databinding-examples/blob/master/java/src/GsonEntryCustomizer.java — it (de)serializes Entry to(from array).
Disclaimer — I have not written nor tested that code, but it seems legit.
If you only encounter such problem once (like in your example), you may not bother making it generic, just write TypeAdapter for your specific pair of 2 different classes. The reading code is quite straightforward:
in.beginArray();
SomeClass1 info1 = gson.getAdapter(SomeClass1.class).read(in);
SomeClass2 info2 = gson.getAdapter(SomeClass2.class).read(in);
in.endArray();
return new SomeContainerClass(info1, info2);
(see https://github.com/cakoose/json-tuple-databinding-examples/blob/master/java/src/GsonEntryCustomizer.java#L52)

Retrofit + GSON deserializer

I have an object like this one:
"choice": {
"000": {
"id": "001",
"label": "test",
"status": "0"
},
"001": {
"id": "001",
"label": "test",
"status": "0"
},
"002": {
"id": "001",
"label": "test",
"status": "0"
},
"003": {
"id": "001",
"label": "test",
"status": "0"
},
"004": {
"id": "001",
"label": "test",
"status": "0"
}
},
How can I parse that object with Gson+Retrofit? Or generate a POJO? There is an easy way of doing this?
Many thanks!
The main idea that all that you have in choice json object is Map:
public class RootObject{
Map <String,ChoiceEntry> choice;
}
public class ChoiceEntry{
String id;
String label;
int status;
}
You can create a POJO by pasting that JSON code into this link: http://pojo.sodhanalibrary.com/.
You posted a snippet that isn't properly formatted. I believe you'll have a multi-class POJO, and that is tricky to work with for certain uses such as listviews.
Let me know how it goes. Retrofit's really nice to use, but extremely annoying to figure out!
There's an addon for intellij/android studio for easy POJO generation.
Disclaimer: I have no affiliation with the project.

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.

Trouble retrieving data from web service using GSON

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...

Categories

Resources