这是我的json值,
{"test":"ruslan","status":"OK"}
如何获得“测试”价值?
这是我的httpclient代码,用于访问api
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");
}
});
答案 0 :(得分:1)
你可以这样做
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);
答案 1 :(得分:0)
首先通过连接到服务器从服务器获取你的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");
答案 2 :(得分:0)
以下是如何解析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");
详情请见This Demo