[英]how to convert json data from string variable to data to display
我想像这样的例子从字符串变量转换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
尝试替换此行:
JSONArray Array = new JSONArray(in);
有了这个 :
JSONObject json = new JSONObject(in);
JSONArray Array = new JSONArray(json.getJSONArray("employees"));
尝试下面的代码:-
JSONObejct j = new JSONObejct(in);
JSONArray Array = j.getJSONArray("employees");
注意:-
{}
表示JSONObject
。 ( {employe}
) []
表示JSONArray
。 ( employee[]
) 您的String in
是具有关键employees
和值JSONArray
的对象。
所以,你需要分析in
作为JSONObject
并获得JSONArray
employees
从该对象。
尝试这个
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();
};
实际上,您的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();
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.