使用ormlite从json读取数据并将其保存在android应用程序中 [英] Reading data from json and saving it in android app using ormlite

查看:64
本文介绍了使用ormlite从json读取数据并将其保存在android应用程序中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是使用 android 数据库工作的新手.我的问题是,我有一个 json 数据,我想在我的 android 应用程序中解析它.具体来说,我想获取该数据并将其保存在我的应用程序数据库中,即 ORMLITE.有没有人有这样的例子,所以请与我分享.任何类型的视频教程或任何内容都会在这里有所帮助.提前致谢

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

推荐答案

好吧,我不使用 ORMLITE,我使用 GreenDao 作为 ORM,但我想这是同一件事.为了解析 JSON,有一些库可以提供帮助,我总是尝试使用 GSON是一个处理对象和 JSON 数据之间序列化的库.网上有很多关于 GSON 的文档和大量的例子.搜索它.我建议使用这种方法,对我来说更好.您也可以使用 org.json.JSON 库解析 JSON.这是一个更手动"的解析器,但可能非常有用.例如:

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:

对于以下 JSON:

{
    "name": "MyName",
    "age": 24
}

您想映射到对象 Person 中,该对象是 ORMLITE 生成的数据模型中的一个类:

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

你可以这样做:

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

这是一种方式.当然 JSON 库有很多函数和类型来帮助你处理 JSON 数据.看看吧.

And that's a way. Of course JSON library has many function and types to help you with JSON data. Check it out.

但是所有使用 GSON 的代码都将简化为:

But all that code with GSON will be reduced to:

Gson gson = new GsonBuilder().create();
Person myPerson = gson.fromJson(myJSONString, Person.class);

所以再次尝试使用 GSON,这是最好的方法.希望有帮助

So again try using GSON, it's the best way. Hope it helps

这篇关于使用ormlite从json读取数据并将其保存在android应用程序中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆