0

我应该如何解析 JSON http://rutube.ru/api/video/editors/?page=1&format=json?我有空显示器。我以http://www.androidhive.info/2012/01/android-json-parsing-tutorial/为例

JSONPARSER.java

public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}

public JSONObject getJSONFromUrl(String url) {

    try {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        HttpResponse httpResponse = httpClient.execute(httpPost);   
        int httpStatus = httpResponse.getStatusLine().getStatusCode();
        if (httpStatus != HttpStatus.SC_OK) {
            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();
                json = sb.toString();
            } catch (Exception e) {
                Log.e("Buffer Error", "Error converting result " + e.toString());
            }

            // try parse the string to a JSON object
            try {
                jObj = new JSONObject(json);
            } catch (JSONException e) {
                Log.e("JSON Parser", "Error parsing data " + e.toString());
            }

        }       
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return jObj;
    }
 }

MAINACTIVITY.java

    public class MainActivity extends ListActivity {
private static String URL_VIDEO = "http";
private static final String TAG_RESULTS = "results";
private static final String VIDEO_OBJECT = "video";
private static final String VIDEO_ID = "id";
private static final String VIDEO_TITLE = "title";
private static final String VIDEO_CREATED_TS = "created_ts";

JSONArray results = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ArrayList<HashMap<String, String>> resultList = new ArrayList<HashMap<String,String>>();
    JSONParser jParser = new JSONParser();
    JSONObject json = jParser.getJSONFromUrl(URL_VIDEO);
        try {               
            results = json.getJSONArray(TAG_RESULTS);
        for (int i = 0; i < results.length(); i++) {
            JSONObject c = results.getJSONObject(i);
            JSONObject video = c.getJSONObject(VIDEO_OBJECT);
            String id = video.getString(VIDEO_ID);
            String title = video.getString(VIDEO_TITLE);
            String created_ts = video.getString(VIDEO_CREATED_TS);
            HashMap<String, String> map = new HashMap<String, String>();
            map.put(VIDEO_ID, id);
            map.put(VIDEO_TITLE, title);
            map.put(VIDEO_CREATED_TS, created_ts);              
            resultList.add(map);
        }
    } catch(JSONException e) {
        e.printStackTrace();
    }
        ListAdapter adapter = new SimpleAdapter(this, resultList, 
                R.layout.list_video_item, 
                new String[] { VIDEO_OBJECT, VIDEO_TITLE, VIDEO_CREATED_TS }, new int[] { R.id.object, R.id.title, R.id.created_ts });
        setListAdapter(adapter);
        ListView lv = getListView();
    }
 }
4

3 回答 3

1

使用Google 的gson 库非常简单:

String json = getJSONFromUrl(URL);// get json from internet as usual
Gson gson = new Gson();
Data data = gson.fromJson(json, Data.class); // let gson handle all the parsing and create Java objects

使用此网站生成Data的课程哪里。我从来没有像你那样做手动 json 解析。

于 2013-10-04T06:35:26.617 回答
0

可能在服务器通信过程中出现故障,您应该在阅读内容之前检查服务器响应代码。在您之后添加此代码httpClient.execute(httpPost);

int httpStatus = httpResponse.getStatusLine().getStatusCode();
switch( httpStatus )
{ 
  case HttpStatus.SC_OK:
  {
    HttpEntity httpEntity = httpResponse.getEntity();
    is = httpEntity.getContent(); 
    // Continue with reading the content here
  }
  default:
  {   
    // here you can print errormessages or information what happened 
  }
}

您的课程的完整代码可能是:

public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}

public JSONObject getJSONFromUrl(String url) {

    try {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        HttpResponse httpResponse = httpClient.execute(httpPost);   
        int httpStatus = httpResponse.getStatusLine().getStatusCode();
        switch( httpStatus )
        { 
          case HttpStatus.SC_OK:
          {
            try {
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
                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();
                json = sb.toString();
            } catch (Exception e) {
                Log.e("Buffer Error", "Error converting result " + e.toString());
            }

            // try parse the string to a JSON object
            try {
                jObj = new JSONObject(json);
            } catch (JSONException e) {
                Log.e("JSON Parser", "Error parsing data " + e.toString());
            }
          }       
          break;
        }
        default:
        {   
           Log.e("JSON Parser", "HttpStatus: "+httpResponse.getStatusLine().getStatusCode() + ", message: " + httpResponse.getStatusLine().getReasonPhrase()  );
          jObj = null;
        }
      }
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return jObj;
    }
 }

这应该可以帮助您查看服务器响应的内容,希望我没有t forget a { in the code ;) The 'default' of the switch is your error section, for every server response except200 OK` 您将获得包含服务器响应的日志条目。

如果您需要更多案例(例如,您是否喜欢403 ForbiddenYust 的不同消息添加更多case HttpStatus.SC_XXXXX块。如果您需要有关Http Statuscodes 的更多信息,请查看 wiki

于 2013-10-04T06:24:52.233 回答
0

那是因为URL_VIDEO您作为参数传递的仅包含http.

于 2013-10-04T06:22:28.547 回答