Reading Data From Json And Saving It In Android App Using Ormlite
Solution 1:
I would utilize the GSON library which is super helpful for handling JSON
https://code.google.com/p/google-gson/
Then you need to create a java class with all of the data that the JSON has that you want to parse.
If your JSON looked like this:
{"id":4854"name":"Charlie""age":35"eye_color":"blue"}
Then you would want to create a class matching that data. THIS IS CASE SENSITIVE.
publicclassDataimplementsSerializable{
privateint id;
privateString name;
privateint age;
privateString eye_color;
}
publicclassItemimplementsSerializable{
}
Now you can create a java object from the JSON:
Gsongson=newGson();
Datadata= gson.fromJson(yourJsonHere, Data.class)
and boom! your data
object is now what your JSON was.
Solution 2:
Ok, I don't use ORMLITE, I'm using GreenDao as ORM but I guess it's the same thing. For parsing a JSON there is some libraries that help, I always try to use GSON that is a library that handle serialization between objects and JSON data. There is a lot of documentation about GSON on the web and plenty of examples. Search for it. I recommend use that approach, for me is the better. Also you can parse a JSON with the org.json.JSON library. This one is more "by hand" parser but could be pretty useful. For example:
for the following JSON:
{"name":"MyName","age":24}
that you want to map into a object Person that is a class from your data model generated by ORMLITE:
publicclassPerson {
privateString name;
private int age;
publicvoidsetName(String name) {
this.name = name;
}
publicvoidsetAge(int age) {
this.age = age;
}
}
You could do something like:
Person myPerson = newPerson();
//This is the use of the org.json.JSON libraryJSONObject jObject = newJSONObject(myJSONString);
myPerson.setName(jObject.getString("name"));
myPerson.setAge(jObject.getInt("age"));
And that's a way. Of course JSON library has many function and types to help you with JSON data. Check it out.
But all that code with GSON will be reduced to:
Gsongson=newGsonBuilder().create();
PersonmyPerson= gson.fromJson(myJSONString, Person.class);
So again try using GSON, it's the best way. Hope it helps
Post a Comment for "Reading Data From Json And Saving It In Android App Using Ormlite"