How to Parse JSON object partially to Java object - java

I am working on a big json output file which is coming as response but I want to parse only some of the fields in my logic.
For ex: The JSON looks like this
{
"lastName":"Smith",
"address":{
"streetAddress":"21 2nd Street",
"city":"New York",
"state":"NY",
"postalCode":10021
},
"age":25,
"phoneNumbers":[
{
"type":"home", "number":"212 555-1234"
},
{
"type":"fax", "number":"212 555-1234"
}
],
"firstName":"John"
}
I have created the necessary JAVA classes and mapping the JSON Object to Java object using GSON. Since, the above JSON is just a sample one in my case I have big one which is generating around 15 classes.
Currently i have to create following classes files:
- Employee.class
- Address.class
- PhoneNumber.class
I want to avoid creating PhoneNumber.class and its nested class using GSON.
Basically My query is like in above json I don't want phoneNumbers and its internal objects so how can i ignore those fields so that i have to construct less Java Class files and still it is mapped to Java Object.
So I want to avoid making classes for PhoneNumbers fields and the nested fields inside PhoneNumbers.

As suggested, Employee and Address classes are all you need:
public class Employee {
private String firstName, lastName;
private int age;
private Address address;
}
public class Address {
private String streetAddress, city, state;
private int postalCode;
}
new Gson().fromJson(json, Employee.class);, where json is the raw JSON string, should then do what you want. Without sharing your code, it is hard to tell why it doesn't work for you.

Related

jackson auto map/deserialize json with unique property

How can i use jackson annotations to automap json to my object. I have nested pojo's for each part of the json but the property name im receiving is a unique id for each object. What should be in the Employees class that will be actually mapping the id and object with names. I have a class below:
public class Company {
#JsonProperty("employees")
private Employees employees;
//getters setters
}
"Employees": {
"1355075": {
"firstName": "john",
"lastName": "doe"
},
"1224423": {
"firstName": "frank",
"lastName": "stevens"
}
}
Your JSON example seems to miss a { at the very beginning.
And there is an spelling mismatch between your
Java class (#JsonProperty("employees"))
and your JSON example ("Employees").
In your JSON example, the part after "Employees":
has the form of a JSON object, mapping strings (the unique ids)
to objects (each with a firstName and lastName).
Now Jackson comes with a generic MapDeserializer which can
deserialize anything looking like a JSON object to a Java Map.
Therefore your Company class should simply have something like this:
#JsonProperty("Employees")
private Map<String, Employee> employees;
You will also need to write an Employee class with
two String properties named firstName and lastName.

Deserializing nested JSON with Jackson [duplicate]

This question already has an answer here:
Flattening nested attributes in Jackson
(1 answer)
Closed 2 years ago.
I am trying to deserialize nested JSON into a single DTO in a Spring Boot application.
The JSON:
{"productId": "xyz123",
"description": "some_description",
"value": "123",
"boughtOnDate": "2020-05-20 14:22:58.000662",
"details": {
"material": "some_material",
/// another 20 entries
}
}
The DTO:
#JsonIgnoreProperties(ignoreUnknown = true)
#Entity
public class Item {
#Id
private String productId;
private String description;
private Integer value;
private Timestamp boughtOnDate;
private String material;
// another 20 fields that are in the nested part of the json
// getters & setters
The current solution I have is to unpack nested json in the Item class like so:
#JsonProperty("details")
private void unpackNestedJson(Map<String, Object> details) {
this.material = (String) details.get("material");
// and another 20 lines for unpackacking the rest from the nested part
While unpackNestedJson works fine and does its job, it feels cumbersome as there is a lot of data to unpack from the nested part of the JSON (all entries below and above 'details' from JSON should go as fields into Item entity class only). My question would be - is there a more simple/elegant way of unpacking the nested JSON into a single DTO? Any help appreciated.
No, i think that's the right way to do, but if you want to explore another option, you could have an Details object inside Item with a material property. Then you could just have some getters/setters with the parent DTO delegating to the material property to still achieve the same behavior.

Will Gson set a field to null when JSON doesn't contain it?

I actually have multiple questions regarding Gson.
The first one being if Gson would set the value of a field to null when the provided JSON does not contain any field matching it.
For example, when the provided JSON features the field name but the class I deserialize it to contains name and avatar, would avatar be null?
The next question is in relation to the above one. When I would set a field with an already predefined value, would Gson override it, even if it isn't provided in the JSON (overrides it to null) or would it simply ignore the field and move on?
And finally would I want to know if Gson would still set a value to name when I would use #SerializedName("username") but the JSON contains name.
I want to update my API, including some bad namings of JSON fields, but I want to make the transition of it for the people using it a smooth as possible, so I want to still (temporary) provide the old field name, while also providing support for the new one. Is that possible using the #SerializedName annotation?
I'm still a beginner with Gson and the Gson User Guide wasn't that helpful for me to answer those two specific questions (Or I overlooked it which would also be possible).
I tried implementing this. Here is my code. I hope the output at the end answers your question.
JSON used:
{
"name": "Robert",
"weather": "19 deg"
}
Main class:
public class GSONExample2 {
private static final String jsonStr = "JSON Mentioned above";
public static void main(String[] args) {
GsonDataExample root = new Gson().fromJson(jsonStr, GsonDataExample.class);
System.out.println(root);
}
}
POJO:
class GsonDataExample {
#SerializedName("username")
private String name;
private String avatar;
#SerializedName(value="weather", alternate = "temperature")
private String weather;
private String nameWithDefault = "Default name";
// getters, setters and toString() implemented
}
Output:
GsonDataExample(name=null, avatar=null, weather=19 deg, nameWithDefault=Default name)
To map multiple keys to same attributes, you can use #SerializedName(value="weather", alternate = "temperature") as shown above.

Changing JSON array to to a pojo object array

I am getting API response on the following format. I am working on Android project
{
Course: [
{
"Year": 2017,
"CourseTitle": "..",
"Quarter": "autumn",
},
{
"Year": 2017,
"CourseTitle": "..",
"Quarter": "autumn",
}
],
Instructor: {
"name": ,
"address":
}
}
My goal is to get Course array of courses, and assign it to the POJO (plain old java object) that I created using online tool. I am also using the GSON library. I did find different implementation online, and I finally used this, and I was able to filter the nested object "Courses", which holds an array object of courses.
JsonParser parser = new JsonParser();
JsonObject element = (JsonObject)parser.parse(response);
JsonElement responseWrapper = element.getAsJsonArray("Courses");
When I look responseWrapper using debugger tool, it holds a JSON array of course (objects). I wanted to assign these data to the "Course" POJO class I created
public class Course implements Parcelable {
private String href;
private int year;
private String courseTitle;
private String quarter;
private String courseTitleLong;
private String curriculumAbbreviation;
private String courseNumber;
}
I added the following line.
Course[] courseList = gson.fromJson(responseWrapper,Course[].class);
CourseList is an array of Course object, but when I look what I got using debugger tool all the field variables are "null". How could I solve this problem? Is there a better way I should have approached? The whole purpose is getting array of course objects so I could manipulate it for display.
Try to rename your fields to exactly match the json response, even case-wise.

desrialize JSON with child array using Jackson annotations?

I'm trying to parse some JSON containing a nested array. I'd like the array to map to a list of child objects within the parent I'm mapping. Here is the (slightly abbreviated) JSON and Java classes
JSON:
{
"id": "12121212121",
"title": "Test Object",
"media$content": [
{
"plfile$audioChannels": 1,
"plfile$audioSampleRate": 18000,
},
{
"plfile$audioChannels": 2,
"plfile$audioSampleRate": 48000,
},
{
"plfile$audioChannels": 2,
"plfile$audioSampleRate": 48000,
}
]
}
Java classes
class MediaObject {
#JsonProperty("id")
private String id;
#JsonProperty("title")
private String title;
#JsonProperty("media$Content")
private List<MediaContent> mediaContent;
... getters/setters ...
}
class MediaContent {
#JsonProperty("plfile$audioChannels")
private int audioChannels;
#JsonProperty("plfile$audioSampleRate")
private int audioSampleRate;
... getters/setters ...
}
I'd like to be able to deserialize using annotations along with the standard mapper code, i.e.
mapper.readValue(jsonString, MediaObject.class)
Everything works fine with the "id" and "title" fields, but my list of MediaContent objects always comes up null. This seems like something Jackson should be able to handle without much trouble, can anyone see what I'm doing wrong here?
The name of the json field is wrong - the attribute is not media$Content, rather media$[c]ontent. Otherwise I do not see why it will not work.

Categories

Resources