我有一个问题当我从服务器中获取文本中的数据时我无法转换为json对象无法转换为json数组我只是从数据库中获取标题和作者并在列表视图中显示
{"document":[{"id":"1","title":"complete refrence of android",
"author":"parag vyas","description":"lnvkzxhbkgbovdghognsdkhogjhlldnglj"}]}
请帮帮我
public class showalbooks extends Activity {
ArrayList<String> mylist = new ArrayList<String>();
String returnString="";
ListView listView ;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.showalbooks);
listView = (ListView) findViewById(R.id.mylist);
new LongRunningGetIO().execute();
}
private class LongRunningGetIO extends AsyncTask <Void, Void, String> {
protected String getASCIIContentFromEntity(HttpEntity entity) throws IllegalStateException, IOException {
InputStream in = entity.getContent();
StringBuffer out = new StringBuffer();
int n = 1;
while (n>0) {
byte[] b = new byte[4096];
n = in.read(b);
if (n>0) out.append(new String(b, 0, n));
}
return out.toString();
}
@Override
protected String doInBackground(Void... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet("http://192.168.1.156/recess/document/document.json");
HttpClient client = new DefaultHttpClient();
HttpResponse response=null;
try{
response = client.execute(httpGet);
}
catch(Exception e){}
System.out.println(response.getStatusLine());
String text = null;
try {
response = httpClient.execute(httpGet, localContext);
HttpEntity entity = response.getEntity();
text = getASCIIContentFromEntity(entity);
} catch (Exception e) {
return e.getLocalizedMessage();
}
String var =text;
try{
JSONArray jArray = new JSONArray(var);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","id: "+json_data.getString("id")+
", title: "+json_data.getString("title")
);
returnString += "\n" +"id:"+ json_data.getString("id")+" "+"Title:"+ json_data.getString("title");
}
}
catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
listView.setFilterText(returnString);
return returnString;
}
protected void onPostExecute(String results) {
if (results!=null) {
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View listview,
int documentid, long documenttitle) {
// TODO Auto-generated method stub
}
});
}
}}}
答案 0 :(得分:1)
JSON数组由JSON对象包围,并且具有id“document”。
而不是:
JSONArray jArray = new JSONArray(var);
你应该:
JSONObject jObj = new JSONObject(var);
JSONArray jArray = jObj.getJSONArray("document");