prolog中不允许内容 - 解析json
我试图使用json文件来存储虚拟Android Studio项目的用户数据,并在尝试测试读取该文件的LoginActivity时,我得到错误prolog中不允许内容 - 解析json
错误:执行任务':app:mergeDebugResources'失败。
/Users/james/projects/cwm/app/src/debug/res/values/users.json:1:1: Error: Content is not allowed in prolog.
{
"users": [
{
"name": "James",
"email": "[email protected]",
"address": "addr1",
"password": "password",
"usertype": "USER"
},
{
"name": "Kayla",
"email": "[email protected]",
"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();
}
}
我搜索计算器和谷歌的解决方案,但大部分答案涉及到XML或JSON解组,我不相信与我在做什么有关,但我可能是错的。提前致谢!
/Users/james/projects/cwm/app/src/debug/res /values/users.json:1:1:错误:内容在prolog中是不允许的。
请从资源文件夹移动你的users.json到资产文件夹,然后再试一次。
因为,getAssets()
方法指的是assets
文件夹。
byte order mark可能会阻止反序列化。检查你的编辑器没有添加一个。
我使用的是Android Studio文本编辑器,我相信它基于IntelliJ平台。它是否添加BOM?我如何检查并关闭它? –
您可以使用任何文本编辑器来切换BOM(例如Notepad ++),以查看它是否存在并将其关闭。 Android Studio中的文本编辑器从来没有给我任何问题。同时检查不可见的字符。 – etan
您的用户数组没有右括号。这是什么导致错误? – BhalchandraSW
@BhalchandraSW我错过了在复制粘贴时,这只是更长的用户列表中的前2个。非常感谢 –