Android 如何获取变量的JSON值?
这是我的json值Android 如何获取变量的JSON值?,android,json,Android,Json,这是我的json值 {"test":"ruslan","status":"OK"} 如何获得测试值 这是我访问api的httpclient代码 AsyncHttpClient client = new AsyncHttpClient(); client.setBasicAuth("user01", "pwd01"); client.get("http://localhost/web/api/getsession", new AsyncHttpResponseHandler() {
{"test":"ruslan","status":"OK"}
如何获得测试值
这是我访问api的httpclient代码
AsyncHttpClient client = new AsyncHttpClient();
client.setBasicAuth("user01", "pwd01");
client.get("http://localhost/web/api/getsession", new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
// in this section, I want to store test value from json to a variable
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
Log.d("Status", "failure");
}
});
你可以这样做
String json = "{\"test\":\"ruslan\",\"status\":\"OK\"}";
String test = "";
try {
JSONObject jsonObject = new JSONObject(json);
test = jsonObject.getString("test");
}catch (JSONException je){
je.printStackTrace();
}
System.out.println("test : " + test);
首先通过连接服务器从服务器获取ur json
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost(http://someJSONUrl/jsonWebService);
// 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();
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
现在你有了JSON,那又怎样
创建JSONObject:
JSONObject jObject = new JSONObject(result);
获取特定字符串的步骤
String aJsonString = jObject.getString("test");
下面是如何解析json的示例
{
"sys":
{
"country":"GB",
"sunrise":1381107633,
"sunset":1381149604
},
"weather":[
{
"id":711,
"main":"Smoke",
"description":"smoke",
"icon":"50n"
}
],
"main":
{
"temp":304.15,
"pressure":1009,
}
}
Java代码
JSONObject sys = reader.getJSONObject("sys");
country = sys.getString("country");
JSONObject main = reader.getJSONObject("main");
temperature = main.getString("temp");
有关更多详细信息,请参见为什么不回答这个问题?@cricket_007你说什么不明白?该问题显示了JSON示例,询问如何获得一个值。这可能回答了如何解析JSON的问题,但并没有回答真正的问题,因为这家伙没有告诉JSON的来源,我假设它来自web服务@cricket当然,但额外的细节其实并不重要,对吧?问题是如何解析JSON,而不是从URL1获取数据http://localhost/web/ 不起作用2你的应用程序中的JSON字符串在哪里?您似乎需要首先将字节[]转换为字符串。