【问题标题】:How to read json data from HttpURLConnection如何从 HttpURLConnection 读取 json 数据
【发布时间】:2016-04-26 06:22:36
【问题描述】:

我正在使用来自 application1 的 HttpURLConnection 从 applicaton2 获取 json 数据。 'application2' 在 Rest 响应对象中设置 json 数据。在 application1 中获得响应后如何读取该 json 数据。

示例代码:

应用程序1:

url = "url to application2";
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();

应用程序2":

List<ModelA> lListModelAs = Entities data;
GenericEntity<List<ModelA>> lEntities = new GenericEntity<List<ModelA>>(lListModelAs) {};
lResponse = Response.ok(lEntities ).build();

我需要从响应的urlConnection中读取上面的json数据。

有什么提示吗?提前致谢。

【问题讨论】:

    标签: java json rest httpurlconnection urlconnection


    【解决方案1】:

    设置您的 HttpURLConnection 之后。

    BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
    
      StringBuilder response = new StringBuilder();
      String line;
    
        JsonObject obj = new JsonParser().parse(reader).getAsJsonObject();
    
    
             boolean status = contentObj.get("status").getAsBoolean();
             String Message = contentObj.get("msg").getAsString();
             String Regno = contentObj.get("regno").getAsString();
            String User_Id = contentObj.get("userid").getAsString();
            String SessionCode = contentObj.get("sesscode").getAsString();
    

    你可以在这里下载 gson jar enter link description here

    【讨论】:

      【解决方案2】:

      使用专用库进行 json 序列化/反序列化,例如 Jackson。它将允许您直接从InputStream 将 json 内容读取到映射响应的 POJO 中。会是这样的:

      MyRestResponse response=objectMapper.readValue(urlConnection.getInput(),MyRestResponse.class);
      

      看起来不错是不是?

      这里有包含使用示例的 Jackson 项目 GitHub 页面。 https://github.com/FasterXML/jackson

      【讨论】:

      • 感谢您的回答。这将读入单个对象,但我希望它作为列表,该怎么做?
      • 您可以拥有任何您想要的对象列表等。例如,MyRestResponse response 你可以拥有List&lt;SomeJSONMappedObjectPOJO&gt; response
      【解决方案3】:

      你可以使用 gson 库 https://github.com/google/gson 用于解析您的数据

      Gson gson = new Gson();
      YourClass objOfYourClass = gson.fromJson(urlConnection.getInputStream(), YourClass.class);
      

      【讨论】:

      • 感谢您的回答。这将读入单个对象,但我希望它作为列表,该怎么做?
      • 一种方法是 YourClass[].class
      猜你喜欢
      • 2016-06-10
      • 2020-08-14
      • 2018-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-25
      • 2016-10-18
      相关资源
      最近更新 更多