2014-09-23 82 views
0

使用下面的代碼我能夠從登錄/ json獲取json信息。使用來自Http的響應get json

如何將其轉換爲我可以使用的東西? 我現在試圖確定用戶是否存在或不存在。 如果它沒有它返回:

`{ 
    "user": null, 
    "sessionId": null, 
    "message": "Invalid email/username and password" 
} 

任何指導將是偉大的。 `

 HttpClient httpClient = new DefaultHttpClient(); 
     // Creating HTTP Post 
     HttpPost httpPost = new HttpPost("http://localhost:9000/auth/login/json"); 
     // Building post parameters 
     // key and value pair 

     List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2); 
     nameValuePair.add(new BasicNameValuePair("user", "user")); 
     nameValuePair.add(new BasicNameValuePair("pw", "password")); 

     // Url Encoding the POST parameters 
     try { 
      httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair)); 
     } catch (UnsupportedEncodingException e) { 
      // writing error to Log 
      e.printStackTrace(); 
     } 

     // Making HTTP Request 
     try { 

      HttpResponse response = httpClient.execute(httpPost); 
      HttpEntity entity = response.getEntity(); 

      // writing response to log 
      Log.d("Http Response:", response.toString()); 
      System.out.println(EntityUtils.toString(entity)); 

     } catch (ClientProtocolException e) { 
      // writing exception to log 
      e.printStackTrace(); 
     } catch (IOException e) { 
      // writing exception to log 
      e.printStackTrace(); 

     } 

回答

1
You can use google GSON to map the json to you model. 

or simply 

JSONObject obj = new JSONObject(jsonresponse.toString()); 

String user = obj.optString("user",null); 

In this way you can access the response. 

if(user == null){ 
    // not authorised or login 
} 
+0

我將如何使用null?我可以通過做if(user = null)來使用它嗎? – Gchorba 2014-09-23 18:55:36

+0

修改了帖子 – 2014-09-23 18:59:57

-1

第一:

List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2); 
    nameValuePair.add(new BasicNameValuePair("user", "user")); 
    nameValuePair.add(new BasicNameValuePair("pw", "password")); 

    // Url Encoding the POST parameters 
    try { 
     httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair)); 
    } 

這是不正確的,下次使用:

JSONObject body = new JSONObject(); 
    body.put("user", "user"); 
    body.put("pw", "password"); 
    String strBody = body.toString(); 

    httpPost.setEntity(new StringEntity(strBody, "UTF-8")); 

對於解析JSON字符串可以使用GSON庫,它是對我來說非常好。只要創建響應的模型,例如:

public class SessionResponse implements Serializable{ 
    @SerializedName("user") 
    private User user; 

    @SerializedName("sessionId") 
    private String sessionId; 

    @SerializedName("message") 
    private String message; 

    } 

就用下一:

String yourResponse = EntityUtils.toString(entity); 
    SessionResponse sessionResponse = new Gson().fromJSON(yourResponse, SessionResponse.class); 

現在你有SessionResponse的對象,可以用它做任何事情。只需注意,您想要轉換的每個類都應該通過實現Serializable接口標記爲「Serializable」。

+0

爲什麼你要序列化模型? – 2014-09-23 18:31:06