我是新來的android開發方面,我知道我想嘗試的一件事是如何使用HTTP Get。我已經完成了整個方法設置,以便發送文本並將結果返回到一個字符串中,但是我想知道的是如何取出該字符串並只提取我真正需要的部分。例如字符串回來Android HTTP獲取和結果字符串
{"id":"124343","name":"somename" }
如果我只是想獲得該開始的id部分我會怎麼做在android中。我正在通過文檔搜索,但到目前爲止我還沒有真正發現任何內容,然後我發現大部分內容都圍繞着使用JSON。
下面是我正在使用的代碼(我已經從幾個不同的職位編譯在一起),但也許我需要切換到使用JSON的解析目的,我只是不知道在哪裏做這個變化
//This class is called after a button is pressed and the HTTPGet string is compiled from text within a textview and a static string (this already works)
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();
String question = questionText.getText().toString();
String newString = httpPath + "?userText=" + question;
Log.i("Message", newString);
HttpGet httpGet = new HttpGet(newString);
String text = null;
try {
HttpResponse response = httpClient.execute(httpGet,
localContext);
HttpEntity entity = response.getEntity();
text = getASCIIContentFromEntity(entity);
} catch (Exception e) {
return e.getLocalizedMessage();
}
return text;
}
protected void onPostExecute(String results) {
if (results != null) {
Log.i("String", results);
}
}
}
ŧ現在我沒有使用JSON,所以還有另一種方法可以在沒有JSON的情況下執行此操作,還是應該切換到使用JSON進行分析?我將用我的代碼更新這篇文章 –
這就是我需要做的,只需將結果字符串轉換爲JSON對象,因爲它已經被格式化了,然後我就可以提取我需要的東西。感謝您的幫助 –
絕對受歡迎。很高興我能幫上忙! –