Json output to exclude field name, but include its class fields - java

Say I have 2 classes, one includes the other
class TestClass {
private int id;
private String name;
private AnotherClass another
}
class AnotherClass {
private String details
}
I would like json output for TestClass to only include AnotherClass's field directly and not show the field another:
{
"id": 1,
"name": "test",
"details": "test details"
}
I found the solution.Use #JsonUnwrapped on field another.
Thanks

If using Jackson, you can use the JsonUnwrapped annotation:
class TestClass {
private int id;
private String name;
#JsonUnwrapped
private AnotherClass another
}
class AnotherClass {
private String details
}

Related

JsonIncludeProperties with JsonUnwrapped

Can I use these annotation for my class to my expected json?
public class Staff {
private String name;
private Integer age;
#JsonUnwrapped
private Staff manager;
.... getter and setter ....
}
{
"name": "Fanny",
"age": 24,
"manager": "Timmy"
}
I know I can use JsonIgnoreProperties but I need to unwrap name only. Any solution? Thanks
You can have a getter for the name that returns a String and annotate it with #JsonPropery,
Can I use these annotation for my class to my expected json?
public class Staff {
private String name;
private Integer age;
#JsonIgnore
private Staff manager;
#JsonProperty("managerName")
public String getManagerName() {
return this.manager.getName();
}
.... getter and setter ....
}

How to rename json object name with java annotation?

How to rename json object name with java annotation?
Object structure in java:
public class ParentClass {
private MyClass myClass;
}
public class MyClass {
private String name;
}
Json will have next view:
{
"myClass":{
"name":"value"
}
}
How can I change name of "myClass" using java/spring annotations, something like
#JsonObjectName("abc")
public class MyClass {
private String name;
}
and json will look like:
{
"abc":{
"name":"value"
}
}
Rename the variable:
private MyClass myClass;
To:
private MyClass abc;
This will yield the correct JSON-output without the use of annotations.
If you still want to use annotations and keep the name of the variable you can use #JsonProperty():
#JsonProperty("abc") // name of the property
private MyClass myClass;
#SerializedName("abc") is also possoble
It depends on the framework you are using. If you are using Jackson Library you can use:
public class ParentClass {
private MyClass myClass;
}
#JsonProperty("abc")
public class MyClass {
private String name;
}
If you are using Gson then
#SerializedName(value = "abc")
public class MyClass {
private String name;
}
Additionally in Gson if you want to use any alternate name for the field during deserialization we can use alternate as below:
#SerializedName(value = "abc", alternate ="xyz")
public class MyClass {
private String name;
}
alternate is to be used only at time of deserialization and GSON will only process/deserialize the last occurence of that field from JSON data.

JAVA JACKSON: serialize a class with two field instead of all class

I need to serialize an entity with only two column when it's called by a foreign key. I'am working in Wildfly, so I'am searching for a jackson solutions.
Suppose I have entity class A
public class A{
private Long id;
private String name;
private String anotherinfo;
private String foo;
...
}
and another class B:
public class B{
private Long id;
private String name;
private A parent;
}
I want to serialize A with all his field when i search for A, but when i need to retrieve an istance of B, i need only two field (an ID and a label)
If I use annotations:
#JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="id")
#JsonIdentityReference(alwaysAsId=true)
private A parent;
i'll return only the id.
The result i want will be like:
B: {
"id" : 1,
"name" : "test",
"parent" : {
"id" : 1,
"name" : 2
}
}
You can use the JsonIgnoreProperties annotation, to disable specific fields for serialization (and deserialization):
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
public class B {
private Long id;
private String name;
#JsonIgnoreProperties({"anotherinfo", "foo"})
private A parent;
Have A extend another class, say C:
class C {
Long id;
String name;
}
class A extends C {
String anotherinfo;
String foo;
...
}
Then, in B:
class B {
Long id;
String name;
#JsonSerialize(as=C.class)
A parent;
}
When you serialize B, its parent field will have just the fields from C, but everywhere else that you serialize an A object you will see all the fields from both A and C.
For more information, take a look at https://github.com/FasterXML/jackson-annotations#annotations-for-choosing-moreless-specific-types
Solved adding a Json Serializer.
I have created an NationJsonSerializer for the parent class:
public class NationJsonSerializer extends JsonSerializer<TNation> {
#Override
public void serialize(TNation value, JsonGenerator jgen, SerializerProvider provider)
throws IOException, JsonProcessingException {
jgen.writeStartObject();
jgen.writeNumberField("id", value.getId());
jgen.writeStringField("name", value.getComune());
jgen.writeStringField("iso", value.getCap());
jgen.writeEndObject();
}
}
Then,in the city class, i put the annotation
#JoinColumn(name = "idtnation",referencedColumnName = "id",nullable = true)
#ManyToOne(targetEntity = TNation.class, fetch = FetchType.EAGER)
#JsonSerialize(using = NationJsonSerializer.class)
private TNation nation;
So, if I use a method Nation n = getNation(long id); i'll receive all columns, but if i use getCity(), I'll receive a simplified version.

Jackson XML: nested field deserialization

I have the following xml
<MyPojo>
<name>Jason</name>
<age>25</age>
<meta>
<occupation>Engineer</occupation>
</meta>
</MyPojo>
I need to deserialize it to the following POJO:
public class MyPojo {
private String name;
private int age;
private String occupation;
}
The problem here is that occupation is wrapped within meta element
You need one more object:
public class MyPojo {
private String name;
private int age;
private Meta meta;
}
public class Meta{
private String occupation;
}
My idea is to replace occupation with an own class. Something like myMeta or whatever you want to call it(be aware in your case like the xml says: meta). This class should cotain the field occupation:
public class Meta
{
private String occupation;
}
After that you only have to add a new field of your new class e.g. myMeta to myPojo. Something like this:
public class MyPojo
{
private String name;
private int age;
private Meta meta;
}
this should avoid
that occupation is wrapped within meta element
Hope that helps!

Trying to convert JSON to Java using GSON

I am completely new to Java but have experience in other languages. I have the following JSON file that I am trying to bring into a java program.
{
"Progression": [
{
"ProgressionName": "An Apple a Day...",
"Steps": [
{
"StepName": "Collect an Apple",
"Type": "COLLECT",
"RewardType": "UNLOCK_CRAFTING",
"Reward": "minecraft:golden_apple"
},
{
"StepName": "Craft a Golden Apple",
"Type": "CRAFT",
"RewardType": "GIVE",
"Reward": "minecraft:diamond"
}
]
},
{
"ProgressionName": "Keeps the Dr Away...",
"Steps": [
{
"StepName": "Collect an Apple",
"Type": "COLLECT",
"RewardType": "UNLOCK_CRAFTING",
"Reward": "minecraft:golden_apple"
},
{
"StepName": "Craft a Golden Apple",
"Type": "CRAFT",
"RewardType": "GIVE",
"Reward": "minecraft:diamond"
}
]
}
]
}
I have the following class that I thought was correct to store the JSON:
public class ProgressionData {
private Progression progresion;
public class Progression {
private String ProgressionName;
private ProgressionSteps Steps;
}
public class ProgressionSteps {
private String StepName;
private String Type;
private String RewardType;
private String Reward;
}
}
This is the call I am using:
BufferedReader br = new BufferedReader(new FileReader(configFile));
ProgressionData progressiondata = new Gson().fromJson(br, ProgressionData.class);
When I debug the code, progressiondata is NULL. I know I am missing something fundamental, and hoping someone can point me in the right direction.
you are trying to map an array of Progression objects to a Progression object,
change from
private Progression progresion;
to
private List<Progression> progresion;
or
private Progression[] progresion;
and the same thing for Progression Step objects
also, don't forget create getters/setters for your members or change access modifiers
Your class is wrong since you have JSONArray inside, please try the following:
public class ProgressionData {
private List<Progression> progresion;
public class Progression {
private String ProgressionName;
private List<ProgressionSteps> Steps;
}
public class ProgressionSteps {
private String StepName;
private String Type;
private String RewardType;
private String Reward;
}
}
Given your example, your base class should look something like the above:
public class ProgressionData {
private Progression[] progresion;
public class Progression {
private String ProgressionName;
private ProgressionSteps[] Steps;
// Add getters and setters
}
public class ProgressionSteps {
private String StepName;
private String Type;
private String RewardType;
private String Reward;
// Add getters and setters
}
// Add getter and setter for "Progression"
}
Notes:
progression and steps fields are actually arrays.
You need to add getters and setters methods for your properties.
You may experience some issues because you are parsing a Property (starting with upper-case P) key from your json to a property (lower-case p). If you try to change your field to Property, the compiler will probably complain because you can't have either a Class and a Field with the same name. In that case, you must look for some GSON parsing options (for ignoring case, for example).
You should update following things to make it work
There is a typo in progresion, it should be Progression. (This might be the primary reason for getting your object as Null, and Name of the variables should match with keys in Json, not classname. You can also use annotation in your POGO class to map the name of the variable with key using #SerializedName("Progression"))
Progression is an array
Steps inside Progression is an array
Please update your ProgressionData as below.
public class ProgressionData {
#SerializedName("Progression")
private List<Progression> progression;
public class Progression {
private String ProgressionName;
private List<ProgressionSteps> Steps;
//Setters and Getters
}
public class ProgressionSteps {
private String StepName;
private String Type;
private String RewardType;
private String Reward;
//Setters and Getters
}
//Setters and Getters
}
Use below code to parse your json,
BufferedReader br = new BufferedReader(new FileReader(configFile));
ProgressionData progressiondata = new Gson().fromJson(br, ProgressionData.class);

Categories