How to get java objects from JSONArray url using Jackson in Android

This is my JSON from the URL https://api.myjson.com/bins/142jr

[
  {
    "serviceNo":"SR0000000001",
    "serDate":"17",
    "serMonth":"DEC",
    "serYear":"2015",
    "serTime":"02.30 AM",
    "serApartmentName":"Galaxy Apartments"
  },
  {
    "serviceNo":"SR0000000002",
    "serDate":"19",
    "serMonth":"JUN",
    "serYear":"2016",
    "serTime":"03.30 AM",
    "serApartmentName":"The Great Apartments"
  }
]

I have one ListView, I want to fill in the details from online JSON, above I gave a link and a json sample, who gave a sample Jackson code in java

Thank you Rajesh Rajendiran

+4
source share
2 answers

To use jackson, you need to create a model class:

[
  {
    "serviceNo":"SR0000000001",
    "serDate":"17",
    "serMonth":"DEC",
    "serYear":"2015",
    "serTime":"02.30 AM",
    "serApartmentName":"Galaxy Apartments"
  },
  {
    "serviceNo":"SR0000000002",
    "serDate":"19",
    "serMonth":"JUN",
    "serYear":"2016",
    "serTime":"03.30 AM",
    "serApartmentName":"The Great Apartments"
  }
]

For the above json, the model class will be:

public class SomeClass {
 private String serviceNo;
 private String serDate;
 private String serMonth;
 private String serYear;
 private String serTime;
 private String serApartmentName;

 @JsonProperty("serviceNo") //to bind it to serviceNo attribute of the json string
 public String getServiceNo() {
  return serviceNo;
 }

 public void setServiceNo(String sNo) { //@JsonProperty need not be specified again
  serviceNo = sNo;
 }

 //create getter setters like above for all the properties.
 //if you want to avoid a key-value from getting parsed use @JsonIgnore annotation

}

Now that you have the above json as a string stored in a variable, say jsonString uses the following code to parse it:

ObjectMapper mapper = new ObjectMapper(); // create once, reuse
ArrayList<SomeClass> results = mapper.readValue(jsonString,
   new TypeReference<ArrayList<ResultValue>>() { } );
results

SomeClass, json .

PS: , Jackson , .

+2

Source: https://habr.com/ru/post/1570749/


All Articles