5

我正在尝试发出一个返回 json 响应的 http get 请求。我需要将 json 响应中的一些值存储在我的会话中。我有这个:

public String getSessionKey(){
    BufferedReader rd  = null;
    StringBuilder sb = null;
    String line = null;
    try {
         URL url = new URL(//url here);
         HttpURLConnection connection = (HttpURLConnection) url.openConnection();
         connection.setRequestMethod("GET");
         connection.connect();
         rd  = new BufferedReader(new InputStreamReader(connection.getInputStream()));
          sb = new StringBuilder();

          while ((line = rd.readLine()) != null)
          {
              sb.append(line + '\n');
          }
          return sb.toString();

     } catch (MalformedURLException e) {
         e.printStackTrace();
     } catch (ProtocolException e) {
         e.printStackTrace();
     } catch (IOException e) {
         e.printStackTrace();
     }

    return "";
}

这将返回字符串中的 JSON:

{ "StatusCode": 0, "StatusInfo": "Processed and Logged OK", "CustomerName": "Mr API"}

我需要在会话中存储 StatusCode 和 CustomerName。如何处理用 java 返回的 JSON?

谢谢

4

6 回答 6

6

使用 JSON 库。这是杰克逊的一个例子:

ObjectMapper mapper = new ObjectMapper();

JsonNode node = mapper.readTree(connection.getInputStream());

// Grab statusCode with node.get("StatusCode").intValue()
// Grab CustomerName with node.get("CustomerName").textValue()

请注意,这不会检查返回的 JSON 的有效性。为此,您可以使用 JSON 模式。有可用的 Java 实现。

于 2013-01-06T18:32:34.387 回答
3

对于会话存储,您可以使用应用程序上下文类:Application,或使用静态全局变量。

要从 HttpURLConnection 解析 JSON,您可以使用如下方法:

public JSONArray getJSONFromUrl(String url) {
    JSONArray jsonArray = null;

    try {
        URL u = new URL(url);
        httpURLConnection = (HttpURLConnection) u.openConnection();
        httpURLConnection.setRequestMethod("GET");
        bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
        stringBuilder = new StringBuilder();

        while ((line = bufferedReader.readLine()) != null) {
            stringBuilder.append(line + '\n');
        }
        jsonString = stringBuilder.toString();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (ProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        httpURLConnection.disconnect();
    }

    try {
        jsonArray = new JSONArray(jsonString);
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return jsonArray;
}
于 2013-09-24T20:36:02.333 回答
1

查看 GSON 库以将 json 转换为对象,反之亦然。

http://code.google.com/p/google-gson/

于 2013-01-06T18:31:44.307 回答
1

你可以试试这个:

JSONObject json = new JSONObject(new JSONTokener(sb.toString()));
json.getInt("StatusCode");
json.getString("CustomerName");

并且不要忘记将其包装成 try-catch

于 2013-05-18T11:44:35.573 回答
1

您可以使用 Gson。这是可以帮助您的代码:

Map<String, Object> jsonMap;  
Gson gson = new Gson();  
Type outputType = new TypeToken<Map<String, Object>>(){}.getType();  
jsonMap = gson.fromJson("here your string", outputType);

现在您知道如何从会话中获取它们并将它们置于会话中。您需要在 classpath 中包含 Gson 库

于 2013-12-23T09:50:21.327 回答
0

我的方法用参数在调用中使用Service或AsyncTask

public JSONArray getJSONFromUrl(String endpoint, Map<String, String> params)
        throws IOException
{
    JSONArray jsonArray = null;
    String jsonString = null;
    HttpURLConnection conn = null;
    String line;

    URL url;
    try
    {
        url = new URL(endpoint);
    }
    catch (MalformedURLException e)
    {
        throw new IllegalArgumentException("invalid url: " + endpoint);
    }

    StringBuilder bodyBuilder = new StringBuilder();
    Iterator<Map.Entry<String, String>> iterator = params.entrySet().iterator();
    // constructs the POST body using the parameters
    while (iterator.hasNext())
    {
        Map.Entry<String, String> param = iterator.next();
        bodyBuilder.append(param.getKey()).append('=')
                .append(param.getValue());
        if (iterator.hasNext()) {
            bodyBuilder.append('&');
        }
    }

    String body = bodyBuilder.toString();
    byte[] bytes = body.getBytes();
    try {

        conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setFixedLengthStreamingMode(bytes.length);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
        // post the request
        OutputStream out = conn.getOutputStream();
        out.write(bytes);
        out.close();
        // handle the response
        int status = conn.getResponseCode();

        if (status != 200) {
            throw new IOException("Post failed with error code " + status);
        }

        BufferedReader  bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuilder stringBuilder = new StringBuilder();


        while ((line = bufferedReader.readLine()) != null)
        {
            stringBuilder.append(line + '\n');
        }

        jsonString = stringBuilder.toString();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (ProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        conn.disconnect();
    }

    try {
        jsonArray = new JSONArray(jsonString);
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return jsonArray;
}
于 2015-09-07T11:43:26.573 回答