问题
I am new in doing work with android database. My question is, I have a json data which i want to parse it in my android application. Specifically i want to take that data and save it in my app database which is ORMLITE. Does anyone have any example of this so please do share with me. Any kind of video tutorial or anything will be helpful here. Thanks in advance
回答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.
public class Data implements Serializable {
private int id;
private String name;
private int age;
private String eye_color;
}
public class Item implements Serializable{
}
Now you can create a java object from the JSON:
Gson gson = new Gson();
Data data = gson.fromJson(yourJsonHere, Data.class)
and boom! your data
object is now what your JSON was.
回答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:
public class Person {
private String name;
private int age;
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
}
You could do something like:
Person myPerson = new Person();
//This is the use of the org.json.JSON library
JSONObject jObject = new JSONObject(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:
Gson gson = new GsonBuilder().create();
Person myPerson = gson.fromJson(myJSONString, Person.class);
So again try using GSON, it's the best way. Hope it helps
来源:https://stackoverflow.com/questions/26265800/reading-data-from-json-and-saving-it-in-android-app-using-ormlite