我是所有这些Android编程的新手。在完成一些教程之后,我成功地解析了一个JSON url。基本上,我想要做的是打印最终得到的字符串(ipString)作为textview或listview。
@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;
}
} 从那里,我应该做什么?
由于
答案 0 :(得分:0)
注意:网址 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"
}
为了简化从网上获取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
}
}