简体   繁体   中英

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

This is my JSON from 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 populate details from online JSON,above i given a link and sample json anybody given sample jackson code in java

Thanks for advance, Rajesh Rajendiran

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 the json the model class would 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 whenever you have the above json as string stored in a variable say jsonString use the following code to parse it:

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

results should now contain two SomeClass objects having the above json parsed as respective objects.

PS: Its been a long time since I have used Jackson for parsing so this code might need some improvements.

If you are getting this as http response then I would suggest to use spring rest template for android. It has support for Message Converters. That way the onus of marshaling and unmarshalling.

[Update] Here is a blog for the same : http://www.journaldev.com/2552/spring-restful-web-service-example-with-json-jackson-and-client-program

Refer Docs for more details:

http://docs.spring.io/spring-android/docs/current/reference/html/rest-template.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM