我在尝试解析从 Django 发送到 Android 的 json 数组字符串时遇到问题。这是json字符串的格式。
[
{
"pk": 1,
"model": "brete.brete",
"fields": {
"contenido": "93iw09if",
"fecha": "2011-05-07 03:06:40",
"codigo_confirmacion": "",
"correo": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="305f595a0870575d51595c1e535f5d" rel="noreferrer noopener nofollow">[email protected]</a>",
"activado": false,
"titulo": "234"
}
},
{
"pk": 2,
"model": "brete.brete",
"fields": {
"contenido": "asoidjfdiso",
"fecha": "2011-05-07 03:08:09",
"codigo_confirmacion": "",
"correo": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4b242221242221220b242221242265282426" rel="noreferrer noopener nofollow">[email protected]</a>",
"activado": false,
"titulo": "ijj"
}
}
]
etc
这就是我获取数据的方式:
//parse json data
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Brete resultRow = new Brete();
resultRow.contenido = json_data.getString("contenido");
resultRow.fecha = json_data.getString("fecha");
resultRow.correo = json_data.getString("correo");
arrayOfWebData.add(resultRow);
}
}
catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
我正在尝试获取 'contenido'
、'fecha'
和 'correo'
的数据,但我没有得到显示的任何行。这不是完整的代码,也许问题出在其他地方,但我有预感这可能是无法使用 json_data.getString() 正确解析嵌套 json 的问题。如有任何帮助,我们将不胜感激。
最佳答案
在获取字段之前,您实际上必须获取“fields”对象:
//parse json data
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject buf = jArray.getJSONObject(i);
JSONObject json_data = buf.getJSONObject("fields");
Brete resultRow = new Brete();
resultRow.contenido = json_data.getString("contenido");
resultRow.fecha = json_data.getString("fecha");
resultRow.correo = json_data.getString("correo");
arrayOfWebData.add(resultRow);
}
}
catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
关于java - 从 Django 到 Android 的 JSON 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12014740/