2017-03-17 75 views
-3

這是我的JSON值,如何獲取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)通過'http://本地主機/網絡/'是行不通2)如果是JSON字符串你的應用?你似乎需要首先將一個byte []轉換爲一個字符串。 –

回答

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); 
0

首先通過連接到它

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現在你有你的JSON,那麼是什麼?

創建一個JSONObject:

JSONObject jObject = new JSONObject(result); 

爲了得到一個特定的字符串

String aJsonString = jObject.getString("test"); 
+0

JSON並不總是來自網站 –

+0

,因爲這個傢伙還沒有告訴json的來源,我認爲它來自於web服務@ cricket_007 –

+0

當然,但是額外的細節應該並不重要,對吧?這個問題問如何解析JSON,而不是從一個URL獲取數據 –

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

+0

爲什麼不只是回答這個問題? –

+0

@ cricket_007你說什麼不讓你? – Roadies

+0

問題顯示示例JSON詢問如何獲取一個值。這可能回答如何解析JSON,但不回答真正問到的問題 –