0

我对所有这些 android 编程都很陌生。在学习了一些教程之后,我成功解析了一个 JSON url。基本上,我想做的是将最后得到的字符串(ipString)打印为文本视图或列表视图。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Log.d("Rami","Rami");
    DefaultHttpClient   httpclient = new DefaultHttpClient(new BasicHttpParams());
    HttpPost httppost = new HttpPost("http://jsonip.com");
    // Depends on your web service
    httppost.setHeader("Content-type", "application/json");

    InputStream inputStream = null;
    String result = null;
    try {
        HttpResponse response = httpclient.execute(httppost);           
        HttpEntity entity = response.getEntity();

        inputStream = entity.getContent();
        // json is UTF-8 by default
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
        StringBuilder sb = new StringBuilder();

        String line = null;
        while ((line = reader.readLine()) != null)
        {
            sb.append(line + "\n");

        }
        result = sb.toString();
        JSONObject jObject = new JSONObject(result);
        String ipString = jObject.getString("ip");
        Log.d("ip", ipString);
    } catch (Exception e) { 
        // Oops
    }
    finally {
        try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
    }




}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

从那里,我该怎么办?

谢谢

4

1 回答 1

0

注意: URL http://jsonip.com返回的“json”无效(根据http://jsonlint.com/上的测试)。

它显示了这一点:

{
    ip: "216.49.181.254",
    about: "/about",
    Pro!: "http://getjsonip.com"
}

实际上应该是这样的:

{
    "ip": "216.49.181.254",
    "about": "/about",
    "Pro!": "http://getjsonip.com"
}

为了简化您从 Web 获取的 JSON,我建议您查看AndroidQuery ( AQuery )。它有一个简单的 JSON 调用,它允许您打印出结果,或者在它返回时对结果进行迭代。

使用这个AQuery库,如果您已经在 AsyncTask 中,您还可以同步获取 JSON。

下面是一些获取 JSON 的示例代码:

public void asyncJson(){

    //perform a Google search in just a few lines of code

    String url = "http://www.google.com/somesearch";             
    aq.ajax(url, JSONObject.class, this, "jsonCallback");

}

public void jsonCallback(String url, JSONObject json, AjaxStatus status){

    if( json != null ){
        //successful ajax call

        String ipString = "";

        try {
            ipString = json.getString("ip");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        Log.d("ip", ipString);//do this if you just want to log the ipString

        //or, do this to set the "ip" string into a TextView 
        //referenced by "R.id.mytextview"
        aq.id(R.id.mytextview).text(ipString); //this is shorthand AQuery syntax
    } else {          
        //ajax error
    }

}
于 2013-08-30T20:28:04.007 回答