本文介绍了Java HttpURLConnection返回JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试发出一个返回json响应的http get请求。我需要将json响应中的一些值存储在我的会话中。我有这个:
I'm trying to make a http get request which returns a json response. I need some of the values from the json response to be stored in my session. I have this:
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:
This returns the JSON in a string:
{ "StatusCode": 0, "StatusInfo": "Processed and Logged OK", "CustomerName": "Mr API"}我需要在会话中存储StatusCode和CustomerName。如何处理使用java返回JSON?
I need to store StatusCode and CustomerName in the session. How do I deal with returning JSON with java?
谢谢
推荐答案您可以使用Gson。以下是帮助您的代码:
You can use Gson. Here is the code to help you:
Map<String, Object> jsonMap; Gson gson = new Gson(); Type outputType = new TypeToken<Map<String, Object>>(){}.getType(); jsonMap = gson.fromJson("here your string", outputType);现在您知道如何从会议中获取并将其放入会议中。 您需要在类路径中包含Gson库。
Now you know how to get from and put those in session. You need to include Gson library in classpath.
更多推荐
Java HttpURLConnection返回JSON
发布评论