2

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"
   }
}

3 Answers 3

4

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;
Sign up to request clarification or add additional context in comments.

Comments

0

@SerializedName("abc") is also possoble

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.