如何使用gson和隐含空间解析本地JSON文件?

时间:2018-07-15 06:15:30

标签: android json

[
  {
    "": 0,
    "Gender": "Girl",
    "Meaning": "Idealistic",
    "Name": "A'adarshini",
    "Origin": "Hindi"
  },
  {
    "": 1,
    "Gender": "Girl",
    "Meaning": "Hope and need",
    "Name": "A'dab",
    "Origin": "Arabic"
  },
  {
    "": 2,
    "Gender": "Girl",
    "Meaning": "Visiting, returning, reward",
    "Name": "A'idah, aida",
    "Origin": "Arabic"
  }
]

我在Android Studio上本地有此JSON文件,我想使用Gson库读取它并实现Room?如何做到这一点?

我正在尝试获取JSON字符串,但出现错误

   String json;
    try {
        InputStream is = getResources().openRawResource(R.raw.names);
        if (is != null) {
            InputStreamReader inputStreamReader = new InputStreamReader(is);
            BufferedReader reader = new BufferedReader(inputStreamReader);

            String line = "";
            StringBuilder sb = new StringBuilder();

            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            is.close();
            json = sb.toString();

            Log.d(TAG, "readData: data recived" + json);

        }
    } catch (IOException e) {

        e.printStackTrace();
    }

1 个答案:

答案 0 :(得分:1)

您可以简单地使用以下代码。

 String jsonOutput; // Your json string
 Type listType = new TypeToken<List<RoomModel>>() {}.getType();
 ArrayList< RoomModel > rooms = new Gson().fromJson(jsonOutput, listType);


public class RoomModel
{
    public int ID,
    public String Gender;
    public String Meaning;
    public String Name;
    public String Origin;
}