如何解析资产中的本地JSON文件?

时间:2017-07-18 20:58:44

标签: android json android-assets

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

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

4 个答案:

答案 0 :(得分:19)

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

在app gradle文件中添加此依赖项:

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

在res文件夹中创建原始文件夹。然后将您的json文件复制到原始文件夹。(最好使用原始文件夹而不是资源)。例如,您有一个名为 my_json.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文件:

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文件:

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

然后将json字符串转换为model:

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

现在你的Json已经转换为模特了! 祝贺!

答案 1 :(得分:1)

首先你需要从资源中读取json文件,你可以使用这个方法

public String readFile(String fileName) throws IOException
{
  BufferedReader reader = null;
  reader = new BufferedReader(new InputStreamReader(getAssets().open(fileName), "UTF-8")); 

  String content = "";
  String line;
  while ((line = reader.readLine()) != null) 
  {
     content = content + line
  }

  return content;

}

然后

String jsonFileContent = readFile("json_in_assets.json");
JSONArray jsonArray = new JSONArray(jsonFileContent);
List<Person> persons = new ArrayList<>();
for (int i=0;i<jsonArray.length();i++)
{
  JSONObject jsonObj = jsonArray.getJSONObject(i);
  Integer id = jsonObj.getInt("id");
  String name = jsonObj.getString("name");
  String phone = jsonObj.getString("phone");
  persons.add(new Person(id , name , phone));
}

答案 2 :(得分:0)

以前的答案效果很好,但是如果您使用的是Kotlin,则可以通过使用kotlin.io包中的类以非常简洁的方式来实现。

val objectArrayString: String = context.resources.openRawResource(R.raw.my_object).bufferedReader().use { it.readText() }
val objectArray = Gson().fromJson(objectArrayString, MyObject::class.java)

如果您想轻松重用,甚至可以变成一个不错的通用扩展方法:

inline fun <reified T> Context.jsonToClass(@RawRes resourceId: Int): T =
        Gson().fromJson(resources.openRawResource(resourceId).bufferedReader().use { it.readText() }, T::class.java)

然后您将这样简单地致电:

context.jsonToClass<MyObject>(R.raw.my_object)

答案 3 :(得分:0)

将json文件放在原始文件夹中,然后在Gson库中可以解析json:

/pgadmin4

您可以将此JsonElemnt用于Gson,或者如果要将json作为字符串,则可以执行以下操作:

Reader reader= new InputStreamReader(getResources().openRawResource(R.raw.json_test));
JsonElement json=new Gson().fromJson(reader,JsonElement.class); 
相关问题