JSON to POJO with nested values
You can create Pojo.class
as mentioned below
public class pojo {
private Title title;
private String link;
private String type;
private String status;
private String slug;
private String modified_gmt;
private String modified;
private Guid guid;
private String date_gmt;
private String date;
private int id;
public Title getTitle() {
return title;
}
public void setTitle(Title title) {
this.title = title;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getSlug() {
return slug;
}
public void setSlug(String slug) {
this.slug = slug;
}
public String getModified_gmt() {
return modified_gmt;
}
public void setModified_gmt(String modified_gmt) {
this.modified_gmt = modified_gmt;
}
public String getModified() {
return modified;
}
public void setModified(String modified) {
this.modified = modified;
}
public Guid getGuid() {
return guid;
}
public void setGuid(Guid guid) {
this.guid = guid;
}
public String getDate_gmt() {
return date_gmt;
}
public void setDate_gmt(String date_gmt) {
this.date_gmt = date_gmt;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public static class Title {
private String rendered;
public String getRendered() {
return rendered;
}
public void setRendered(String rendered) {
this.rendered = rendered;
}
}
public static class Guid {
private String rendered;
public String getRendered() {
return rendered;
}
public void setRendered(String rendered) {
this.rendered = rendered;
}
}
}
And you can parse list
try {
JSONObject jsonObject = new JSONObject("YOUR_RESPOSE");
JSONArray data = jsonObject.getJSONArray("data");
Type listType = new TypeToken<ArrayList<pojo>>() {
}.getType();
ArrayList<pojo> list =new Gson().fromJson(data.toString(), listType);
} catch (JSONException e) {
e.printStackTrace();
}
Mapping nested JSON to a Java POJO
Users
JSON Object
is wrapped in JSON Array
which is wrapped in root JSON Object
. You need to use collections types:
TypeReference<Map<String, List<Users>>> usersType = new TypeReference<Map<String, List<Users>>>() {};
Map<String, List<Users>> wrappedUsers = mapper.readValue(body, usersType);
List<Users> users = wrappedUsers.values().stream().flatMap(Collection::stream).collect(Collectors.toList());
Or create wrapper class:
class UsersHolder {
public List<Users> users;
//getters, setters
}
which you can use as:
UsersHolder wrappedUsers = mapper.readValue(body, UsersHolder.class);
System.out.println(wrappedUsers.users);
See also:
- Array of JSON Object to Java POJO
- Java 8 flatMap example
Format of POJO for nested JSON?
You can try below code to convert your json string to Pojo object with required fields using Gson library.
Gson gson = new Gson();
JsonArray jsonArray = gson.fromJson (jsonString, JsonElement.class).getAsJsonArray(); // Convert the Json string to JsonArray
JsonObject jsonObj = jsonArray.get(0).getAsJsonObject(); //Get the first element of array and convert it to Json object
Pojo pojo = gson.fromJson(jsonObj.get("data").toString(), Pojo.class); //Get the data property from json object and convert it to Pojo object
or you can define your nested Pojo class to parse it.
class Pojo
{
private String item1;
private String item2;
//Setters and Getters
}
class Data
{
private Pojo data;
//Setters and Getters
}
ArrayList<Data> yourArray = new Gson().fromJson(jsonString, new TypeToken<List<Data>>(){}.getType());
EDIT : Try below code to get value1 and value2 using Retrofit.
class Pojo
{
private String item1;
private String item2;
//Setters and Getters
}
class Data
{
private Pojo data;
//Setters and Getters
}
class MyData
{
private ArrayList<Data> dataList;
//Setters and Getters
}
IService service = restAdapter.create(IService.class);
MyData data = service.getData();
ArrayList<Data> list = data.getDataList(); // Retrive arraylist from MyData
Data obj = list.get(0); // Get first element from arraylist
Pojo pojo = obj.getData(); // Get pojo from Data
Log.e("pojo", pojo.item1 + ", " + pojo.item2);
Nested map of a pojo with Jackson
First, in order to deserialize the nested Error
objects containing final fields, it is needed to mark the all-args constructor with @JCreator
annotation and use @JsonProperty
to set the values properly:
public class Error {
private final String errcode;
private final String error;
@JsonCreator
public Error(@JsonProperty("errcode") String errcode, @JsonProperty("error") String error) {
this.errcode = errcode;
this.error = error;
}
// ... getters/toString, etc.
}
Then ObjectMapper::convertValue
should be used to read the contents of the map from the JsonNode
:
String json = ...; // input JSON string
ObjectMapper om = new ObjectMapper();
JsonNode node = om.readTree(json); // throws JsonProcessingException
Map<String, Error> errors = om.convertValue(
node.get("errors"), new TypeReference<Map<String, Error>>(){}
);
errors.forEach((k, v) -> System.out.println(k + " = " + v));
// -> firstError = {errcode='1234', error='The 1. message'}
// -> secondError = {errcode='5678', error='The 2. message'}
Mapping nested JSON values in a Java class
You can club all the supporting classes in one class like below :
@Data
public class Start {
@JsonProperty("dateTime")
public Date dateTime;
public static class Venue {
@JsonProperty("name")
public String name;
}
@Data
public static class Classification {
@JsonProperty("name")
public String name;
}
@Data
public static class Embedded2 {
@JsonProperty("venues")
public List<Venue> venues;
}
@Data
public static class Dates {
@JsonProperty("start")
public Start start;
@JsonProperty("classifications")
public List<Classification> classifications;
@JsonProperty("_embedded")
public Embedded2 _embedded;
}
@Data
public static class Event {
@JsonProperty("name")
public String name;
@JsonProperty("dates")
public Dates dates;
}
@Data
public static class Embedded {
@JsonProperty("events")
public List<Event> events;
}
@Data
public static class Root {
@JsonProperty("_embedded")
public Embedded _embedded;
}
}
You can test (I am using Jackson for deserialization)
create ObjectMapper class and deserialize into a Root class
public class TestJson {
public static void main(String[] args) {
ObjectMapper objectMapper = new ObjectMapper();
try {
Start.Root root = objectMapper.readValue(new File("C:\\Anurag\\Development\\CodeBase\\demo\\src\\main\\java\\com\\example\\demo\\domain\\testJson\\test.json"), Start.Root.class);
System.out.println(root);
} catch (Exception e) {
e.printStackTrace();
}
}
}
-When debugging, you'll notice that our objects have been filled accordingly:
**Changes done as per your requiement **
@Data
public class EventList {
@Getter
@JsonProperty("_embedded")
private Events events;
@Data
public static class Venue {
@JsonProperty("name")
public String name;
}
@Data
public static class Classification {
@JsonProperty("name")
public String name;
}
@Data
public static class Embedded2 {
@JsonProperty("venues")
public List<Venue> venues;
}
@Data
public static class Dates {
@JsonProperty("start")
public Start start;
@JsonProperty("classifications")
public List<Classification> classifications;
@JsonProperty("_embedded")
public Embedded2 _embedded;
}
@Data
public static class EventDetails {
@JsonProperty("name")
public String name;
@JsonProperty("dates")
public Dates dates;
}
@Data
public static class Events {
@JsonProperty("events")
public List<EventDetails> eventsList;
}
@Data
public static class Start {
@JsonProperty("dateTime")
public Date dateTime;
}
}
public class TestJson {
public static void main(String[] args) {
List<EventList.EventDetails> anyCity = findEventByCity("any city");
anyCity.stream().forEach(p-> {
System.out.println(p);
});
}
@SneakyThrows
static List<EventList.EventDetails> findEventByCity(String city) {
ObjectMapper objectMapper = new ObjectMapper();
EventList eventList = objectMapper.readValue(new File("C:\\Anurag\\Development\\CodeBase\\demo\\src\\main\\java\\com\\example\\demo\\domain\\testJson\\test.json"), EventList.class);
List<EventList.EventDetails> eventsList = eventList.getEvents().getEventsList();
return eventsList;
}
}
Parse JSON nested object to Java POJO with GSON
Not sure how to do it with a List
, but this is how to do it with Map
:
Map<String, Ping> map = gson.fromJson(json, new TypeToken<Map<String, Ping>>(){}.getType());
Then you can just map.values()
if you want all the values.
Related Topics
Regular Expression to Match a Backslash Followed by a Quote
How to Scroll to the Bottom of a Recyclerview? Scrolltoposition Doesn't Work
Refactor Multiple If' Statements in Java-8
Gson Expected Begin_Array But Was String At Line 1 Column 62
Java Program to Find Palindrome Numbers in Given Range
How to Center Crop a Background Image of Linear Layout
Java.Sql.Sqlexception: Field Doesn't Have a Default Value
Java Properties - How to Create Dynamic Properties
Keytool Error Bash: Keytool: Command Not Found
Saveastextfile() to Write the Final Rdd as Single Text File - Apache Spark
Typecasting an Object from Parent Class to Child
How to Use Different Jsonproperty on Serialize & Deserialize Using Jackson API
How to Change Cookie Processor to Legacycookieprocessor in Tomcat 8
Unit Testing Private Functions in Junit With Mockito
How to Change the Colors of Text and Background for Cmd in Java