1

I am using HttpURLConnection from application1 to get json data from applicaton2. 'applicaton2' sets json data in Rest response object. How can i read that json data after getting response in application1.

Sample code:

Application1:

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

Application2":

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

I need to read above json data from urlConnection from response.

Any hints? Thanks in advance.

user1770589
  • 375
  • 1
  • 6
  • 19

3 Answers3

2

After setting up your 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();

You can download the gson jar here enter link description here

SilenceCodder
  • 2,874
  • 24
  • 28
1

Use dedicated library for json serialization/deserialization, Jackson for example. It will allow you to read json content directly from InputStream into POJOs that maps the response. It will be something like that:

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

Looking good isnt it??

Here you have Jackson project GitHub page with usage examples. https://github.com/FasterXML/jackson

Antoniossss
  • 31,590
  • 6
  • 57
  • 99
1

You can use gson library https://github.com/google/gson for parsing your data

Gson gson = new Gson();
YourClass objOfYourClass = gson.fromJson(urlConnection.getInputStream(), YourClass.class);
peeyush pathak
  • 3,663
  • 3
  • 19
  • 25