我一直在尝试将Json解析为A ListView,但是当我这样做时,我得到了;
03-04 14:43:45.345: E/log_tag(16519): Error parsing data org.json.JSONException: No value for items
它以某种方式无法从Json对象中获取项目。
这是我用于它的代码;
getJSON.java
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class getJSON {
public static JSONObject getJSONfromURL(String url){
InputStream is = null;
String result = "";
JSONObject jArray = null;
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("NO CONNECTION", "Error in http connection "+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("CANT CONVERT DATA", "Error converting result "+e.toString());
}
try{
jArray = new JSONObject(result);
}catch(JSONException e){
Log.e("CANT READ DATA", "Error parsing data "+e.toString());
}
return jArray;
}
}
和
listview.java
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.listplaceholder);
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
//Get the data (see above)
JSONObject json = getJSON.getJSONfromURL("http://gdata.youtube.com/feeds/api/users/UKFDubstep/uploads?v=2&alt=jsonc");
try{
final JSONArray array = json.getJSONArray("items");
//Loop the Array
for(int i=0;i < array.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = array.getJSONObject(i);
map.put("id", String.valueOf(i));
map.put("title", "" + e.getString("title"));
map.put("viewCount", "Views: " + e.getString("viewCount"));
mylist.add(map);
}
}catch(JSONException e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}
ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.dubstep,
new String[] { "title", "viewCount" },
new int[] { R.id.item_title, R.id.item_subtitle });
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
@SuppressWarnings("unchecked")
HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);
Toast.makeText(dubstep.this, "ID '" + o.get("id") + "' was clicked.", Toast.LENGTH_SHORT).show();
}
});
}
我不知道它出了什么问题。
有任何帮助吗? 感谢。
编辑: json输出
03-04 15:30:29.955: I/json(19109): {"error":{"message":"Response contains no content type","errors":[{"internalReason":"Response contains no content type","domain":"GData","code":"missingContentType"}],"code":400},"apiVersion":"2.1"}
编辑json链接; http://gdata.youtube.com/feeds/api/users/UKFDubstep/uploads?v = 2&amp; alt = jsonc
答案 0 :(得分:1)
通过查看JSON结果(打开你的示例url),我看到'items'在另一个JSONObject中。所以我相信你需要这样做:
JSONObject data = json.getJSONObject('data');
JSONArray array = data.getJSONArray('items');
答案 1 :(得分:0)
你不需要getJSON.java,只有你应该做的才能使它工作:
private static String URL = "http://gdata.youtube.com/feeds/api/users/UKFDubstep/uploads?v=2&alt=jsonc";
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.listplaceholder);
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
try{
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpGet request = new HttpGet(URL);
HttpResponse response = httpclient.execute(request);
HttpEntity resEntity = response.getEntity();
String _response = EntityUtils.toString(resEntity); // content will be consume only once
Log.i(".......",_response);
JSONObject json = new JSONObject(_response);
JSONArray jarray = json.getJSONArray("items");
//Loop the Array
for(int i=0;i < array.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = array.getJSONObject(i);
map.put("id", String.valueOf(i));
map.put("title", "" + e.getString("title"));
map.put("viewCount", "Views: " + e.getString("viewCount"));
mylist.add(map);
}
}catch(JSONException e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}
ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.dubstep,
new String[] { "title", "viewCount" },
new int[] { R.id.item_title, R.id.item_subtitle });
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
@SuppressWarnings("unchecked")
HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);
Toast.makeText(dubstep.this, "ID '" + o.get("id") + "' was clicked.", Toast.LENGTH_SHORT).show();
}
});
}
但是现在你应该解析JSON数据不应该在UI线程中执行。您需要扩展AsyncTask并在doInBackgound()方法中执行该工作,因此您可以在单独的线程中进行解析,而不是在UI中进行解析... AsyncTask