prolog中不允许使用内容 - 解析json

时间:2017-04-10 12:49:01

标签: android json parsing android-studio

我试图使用json文件来存储虚拟Android Studio项目的用户数据,并且在尝试测试读取文件的LoginActivity时,我收到了错误

错误:任务':app:mergeDebugResources'执行失败。

  

/Users/james/projects/cwm/app/src/debug/res/values/users.json:1:1:错误:prolog中不允许使用内容。

{
  "users": [
    {
      "name": "James",
      "email": "j@gmail.com",
      "address": "addr1",
      "password": "password",
      "usertype": "USER"
    },
    {
      "name": "Kayla",
      "email": "k@gmail.com",
      "address": "addr1",
      "password": "password",
      "usertype": "MANAGER"
    }
  ]
}

以下是我认为导致错误的LoginActivity中的代码:

private String loadJSONFromAsset() {
    String json = null;
    try {
        InputStream is = this.getAssets().open("users.json");
        int size = is.available();
        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();
        json = new String(buffer, "UTF-8");
    } catch (IOException ex) {
        ex.printStackTrace();
        return null;
    }
    return json;
}

private void parseJ() {
    try {
        JSONObject jsonObject = new JSONObject(loadJSONFromAsset());
        if(jsonObject != null) {
            JSONArray jsonArray = jsonObject.getJSONArray("users");
            if(jsonArray != null) {
                for(int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jo = jsonArray.getJSONObject(i);
                    if(jo != null) {
                        String name = (String) jo.get("name");
                        String email = (String) jo.get("email");
                        String address = (String) jo.get("address");
                        String password = (String) jo.get("password");
                        String userType = (String) jo.get("usertype");

                        User u = new User(name, email, address, password);
                        u.setUserType(userType);
                        userList.put(email, u);
                        a.setMessage(u.toString());
                        a.show();
                    }
                }
            }
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

}

我已经搜索了stackoverflow和Google的解决方案,但大多数答案都与XML或JSON解组有关,我不相信这与我正在做的事情有关,但我可能错了。提前谢谢!

2 个答案:

答案 0 :(得分:0)

byte order mark可能会阻止反序列化。检查您的编辑器是否添加了一个。

答案 1 :(得分:0)

/ Users / james / projects / cwm / app / src / debug / res /values/users.json:1:1:错误:prolog中不允许使用内容。

请将users.json从 res 文件夹移至 assets 文件夹,然后重试。

因为,getAssets()方法是指assets文件夹。

相关问题