我有一个JSON
文件想从中检索详细信息,只是在文本视图中显示它。
我得到了消息和成功的价值,但不是其他的,例如学生和细节
我的JSON:
{
"message":"Thank you for your patience.",
"student":{
"name":"aaaa",
"mark":"55",
"dob":"10-09-1990"},
"details":{
"fathername":"bbbb",
"mothername":"ccccc",
"address":"xxxxxx"},
"success":true
}
我的Java代码
@Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
@Override
protected void onPostExecute(JSONObject json) {
try {
// Getting JSON Array
// Storing JSON item in a Variable
String success = json.getString("success"); // I get values for both of these
String message = json.getString("message");
String StudentName = null;
// I Tried This/*
user = json.getJSONArray("student");
for (int i = 0; i < user.length(); i++) {
email = user.getJSONObject(i).getString("name");
}*/
//Set JSON Data in TextView
uid.setText(success);
name1.setText(message);
email1.setText(email);
} catch (JSONException e) {
e.printStackTrace();
}
}
我尝试了以上代码,但收到了错误
01-06 18:26:15.120: W/System.err(2110): org.json.JSONException: Value {"name":"aaaa","mark":"55","dob":"10-09-1990"} at student of type org.json.JSONObject cannot be converted to JSONArray
帮我解决这个问题。
答案 0 :(得分:3)
user = json.getJSONArray("student");
学生不是jsonarray
"student":{
student是一个jsononbject
所以改变
JSONObject user = json.getJSONObject("student");
然后
String name = user.getString("name");
@Override
protected void onPostExecute(JSONObject json)
super.onPostExecute(json); // missing
// although this does not lead to any error
答案 1 :(得分:3)
student是一个JSONObject,你必须像JSONObject一样管理它。变化
user = json.getJSONArray("student");
到
JSONObject user = json.getJSONObject("student");
答案 2 :(得分:0)
{ “消息”:“谢谢你的耐心等待。”, “学生”:{ “名”: “AAAA”, “标志”: “55”, “出生日期”: “1990年10月9日”}, “细节”:{ “fathername”: “BBBB” “mothername”: “CCCCC”, “地址”: “XXXXXX”}, “成功”:真 }
Android代码:
JsonObject jsonobj = new JsonObject("your json String");
String message = jsonobj.getString("message");
String success = jsonobj.getString("success");
JsonObject studentObj = jsonobj.getJsonObject("student");
String name = studentObj.getString("name");
String mark= studentObj.getString("mark");
JsonObject detailsObj = jsonobj.getJsonObject("details");
String fathername= detailsObj.getString("fathername");
String mothername= detailsObj.getString("mothername");