我想从字符串变量中转换json数据,如下例所示:
String in = "{'employees': [{'firstName':'John' , 'lastName':'Doe' },"
+ "{ 'firstName' : 'Anna' , 'lastName' :'Smith' },"
+ "{ 'firstName' : 'Peter' , 'lastName' : 'Jones' }]}";
try {
String country = "";
JSONArray Array = new JSONArray(in);
for (int i = 0; i < Array.length(); i++) {
JSONObject sys = Array.getJSONObject(i);
country += " " + sys.getString("firstName");
}
Toast.makeText(this, country, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
// TODO Auto-generated catch block
Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
};
当我尝试此代码时,我收到此错误:
Error parsing data org.json.JSONException: Value 0 of type java.lang.Integer cannot be
converted to JSONObject
答案 0 :(得分:0)
尝试替换此行:
JSONArray Array = new JSONArray(in);
有了这个:
JSONObject json = new JSONObject(in);
JSONArray Array = new JSONArray(json.getJSONArray("employees"));
答案 1 :(得分:0)
尝试以下代码: -
JSONObejct j = new JSONObejct(in);
JSONArray Array = j.getJSONArray("employees");
请注意: -
{}
表示JSONObject
。 ({employe}
)[]
表示JSONArray
。 (employee[]
)答案 2 :(得分:0)
您的字符串in
是一个键为employees
且值为JSONArray
的对象。
因此,您需要将in
解析为JSONObject
并从该对象获取JSONArray
employees
。
答案 3 :(得分:0)
试试这个
String in = "{'employees': [{'firstName':'John' , 'lastName':'Doe' },"
+ "{ 'firstName' : 'Anna' , 'lastName' :'Smith' },"
+ "{ 'firstName' : 'Peter' , 'lastName' : 'Jones' }]}";
try {
String country = "";
JSONObject jObj = new JSONObject(in);
JSONArray jArray = jObj.getJSONArray("employees");
for(int j=0; j <jArray.length(); j++){
JSONObject sys = jArray.getJSONObject(j);
country += " " + sys.getString("firstName");
}
Toast.makeText(this, country, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
};
答案 4 :(得分:0)
实际上你的JSON格式错误。
使用以下字符串
String in = "{\"employees\": [{\"firstName\": \"John\",\"lastName\": \"Doe\"},{\"firstName\": \"Anna\",\"lastName\": \"Smith\"},{\"firstName\": \"Peter\",\"lastName\": \"Jones\"}]}";
try {
String country = "";
JSONObject jObj = new JSONObject(in);
JSONArray jArray = jObj.getJSONArray("employees");
for(int j=0; j <jArray.length(); j++){
JSONObject sys = jArray.getJSONObject(j);
country += " " + sys.getString("firstName");
}
Toast.makeText(this, country, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
};