如何解析资产中的本地JSON文件? [英] How to parse local JSON file in assets?

查看:170
本文介绍了如何解析资产中的本地JSON文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的资产文件夹中有一个JSON文件.该文件具有一个带有数组的对象.该数组有150多个对象,每个对象都有三个字符串.

I have a JSON file in my assets folder. That file has one object with an array. The array has 150+ objects with each having three strings.

对于这150多个对象,我想提取每个字符串并创建一个Java模型对象,并传递三个字符串.我在android JSON解析中找到的所有教程都是从我不想做的URL中获取JSON.

For each of these 150+ objects I want to extract each string and create a java model object with it passing the three strings. All the tutorials I'm finding on android JSON parsing are fetching the JSON from a url which I don't want to do.

推荐答案

您应该使用 Gson库 作为 json解析器.

将此依赖项添加到应用gradle文件中:

add this dependency in app gradle file :

compile 'com.google.code.gson:gson:2.8.1'

在res文件夹中创建原始文件夹.然后将您的json文件复制到原始文件夹(最好使用原始文件夹而不是资产).例如,您有一个名为 my_json.json

create raw folder in res folder. then copy your json file to raw folder.(its better to use raw folder instead of assets). for example you have this json file named my_json.json

{
  "list": [
    {
      "name": "Faraz Khonsari",
      "age": 24
    },
    {
      "name": "John Snow",
      "age": 28
    },
    {
      "name": "Alex Kindman",
      "age": 29
    }
  ]
} 

然后创建您的模型类:

public class MyModel {
        @SerializedName("list")
        public ArrayList<MyObject> list;

       static public class MyObject {
            @SerializedName("name")
            public String name;
            @SerializedName("age")
            public int age;
        }
    }

然后您应该创建一个函数来读取json文件:

then you should create a function to read your json file :

public String inputStreamToString(InputStream inputStream) {
        try {
            byte[] bytes = new byte[inputStream.available()];
            inputStream.read(bytes, 0, bytes.length);
            String json = new String(bytes);
            return json;
        } catch (IOException e) {
            return null;
        }
    }

然后读取您的json文件:

then read your json file:

String myJson=inputStreamToString(mActivity.getResources().openRawResource(R.raw.my_json));

然后将json字符串转换为模型:

then convert json string to model:

MyModel myModel = new Gson().fromJson(myJson, MyModel.class);

现在您的Json已转换为模型! 恭喜!

now your Json have been converted to a model ! Congratulation!

这篇关于如何解析资产中的本地JSON文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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