使用来自Http的响应获取json

时间:2014-09-23 18:15:10

标签: android json http

使用以下代码,我可以从login / json获取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();

        }

2 个答案:

答案 0 :(得分: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
}

答案 1 :(得分:-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的对象,可以做任何事情。请注意,您要转换的每个类都应标记为&#34; Serializable&#34;实现Serializable接口。