如何从HttpURLConnection读取json数据

时间:2016-01-20 12:00:34

标签: java json rest httpurlconnection urlconnection

我正在使用application1的HttpURLConnection从applicaton2获取json数据。 ' applicaton2'在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数据。

任何提示?提前谢谢。

3 个答案:

答案 0 :(得分:1)

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

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

好看不是吗?

这里有杰克逊项目GitHub页面及其用法示例。 https://github.com/FasterXML/jackson

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

设置HttpURLConnection之后。

a = 110
b = 100
c = a - b
d = a - 10
if a > b:
    if (a - b) <= 10:
        print "This is almost Matching"
    else:
        print "This is not at Matching"
else:
    if (b - a) <= 10:
        print "This is almost Matching"
    else:
        print "This is not at Matching"

您可以在enter link description here

处下载gson jar。