How to change a field name in JSON using Jackson
Have you tried using @JsonProperty?
@Entity
public class City {
@id
Long id;
String name;
@JsonProperty("label")
public String getName() { return name; }
public void setName(String name){ this.name = name; }
@JsonProperty("value")
public Long getId() { return id; }
public void setId(Long id){ this.id = id; }
}
Rename fields in object with Jackson
I strongly advise you to use DTOs. See why in this answer.
Alternatively you could use @JsonView
. From Jackson 2.9, you could use @JsonAlias
, which works only for deserialization.
Jackson Java to JSON object mapper modifies field's name
Oleksandr's comment pointed in the right direction. Indeed there is a getParticipantsList() that Jackson seems to take into account when determining the JSON field name. However, as I wrote before, I am not able to make any changes there, considering it is a third party object.
But, with a better understanding of what causes the problem, I was able to come up with a solution:
mapper.setVisibilityChecker(mapper.getVisibilityChecker().withFieldVisibility(Visibility.ANY).withGetterVisibility(Visibility.NONE).withIsGetterVisibility(Visibility.NONE));
or
mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
mapper.setVisibility(PropertyAccessor.GETTER, Visibility.NONE);
mapper.setVisibility(PropertyAccessor.IS_GETTER, Visibility.NONE);
Jackson: How to edit existing property to the JSON without modifying the POJO?
Mixins
The easiest way to modify the output of Jackson without adding annotations to the original POJO is using mixins.
Just define a mixin-class with the necessary annotations and indicate to Jackson that you want to use the mixin when serializing the original object.
private static class MyPojoMixin {
@JsonProperty("cust_id")
private String id;
}
public String serializeWithMixin(MyPojo p) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
mapper.addMixIn(MyPojo.class, MyPojoMixin.class);
return mapper.writeValueAsString(p);
}
Custom property naming strategy
If you need to programmatically change the field-name, you might not be able to use the mixin solution. You could then use a custom PropertyNamingStrategy:
public class IdRenamingStrategy extends PropertyNamingStrategy {
private final PropertyNamingStrategy inner;
private final String newIdPropertyName;
public IdRenamingStrategy(String newIdPropertyName) {
this(PropertyNamingStrategy.LOWER_CAMEL_CASE, newIdPropertyName);
}
public IdRenamingStrategy(PropertyNamingStrategy inner, String newIdPropertyName) {
this.inner = inner;
this.newIdPropertyName = newIdPropertyName;
}
private String translate(String propertyName) {
if ("id".equals(propertyName)) {
return newIdPropertyName;
} else {
return propertyName;
}
}
@Override
public String nameForField(MapperConfig<?> config, AnnotatedField field, String defaultName) {
return inner.nameForField(config, field, translate(defaultName));
}
@Override
public String nameForGetterMethod(MapperConfig<?> config, AnnotatedMethod method, String defaultName) {
return inner.nameForGetterMethod(config, method, translate(defaultName));
}
@Override
public String nameForSetterMethod(MapperConfig<?> config, AnnotatedMethod method, String defaultName) {
return inner.nameForSetterMethod(config, method, translate(defaultName));
}
@Override
public String nameForConstructorParameter(MapperConfig<?> config, AnnotatedParameter ctorParam, String defaultName) {
return inner.nameForConstructorParameter(config, ctorParam, translate(defaultName));
}
}
This can be used like this:
public String serializeWithPropertyNamingStrategy(MyPojo p) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
mapper.setPropertyNamingStrategy(new IdRenamingStrategy("cust_id"));
return mapper.writeValueAsString(p));
}
How to convert JSON field name to Java bean class property with Jackson
Just a quick solution, if the object is such that, that all of it object is a container object you can receive the JSON inside and JSONObject you may use below code
import java.io.IOException;
import org.json.JSONException;
import org.json.JSONObject;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class TestSO {
public static void main(String[] args) throws JsonParseException, JsonMappingException, JSONException, IOException {
String jsonString = "{\r\n" +
" \"Container1\": {\r\n" +
" \"active\": true\r\n" +
" },\r\n" +
" \"Container2\": {\r\n" +
" \"active\": false\r\n" +
" },\r\n" +
"}";
JSONObject jsonObject = new JSONObject(jsonString);
ObjectMapper mapper = new ObjectMapper();
for (String key : jsonObject.keySet()) {
Container container = mapper.readValue(jsonObject.get(key).toString(), Container.class);
System.out.println(container);
}
}
static class Container{
private String name;
private Boolean active;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Boolean getActive() {
return active;
}
public void setActive(Boolean active) {
this.active = active;
}
@Override
public String toString() {
return "Container [name=" + name + ", active=" + active + "]";
}
}
}
How to map JSON field names to different object field names?
Probably it's a bit late but anyway..
you can rename a property just adding
@JsonProperty("contractor")
And by default Jackson use the getter and setter to serialize and deserialize.
For more detailed information: http://wiki.fasterxml.com/JacksonFAQ
Change one field from string to json object in jackson
Adding @JsonRawValue
did the trick.
public class Employee {
private String name;
@JsonProperty("employeeDetails")
@JsonRawValue
private String employeeDetailsBlob;
// getters and setters
}
Related Topics
How to Pass Arithmetic Operators to a Method in Java
Problem with "Scopes" of Variables in Try Catch Blocks in Java
Run a Command Over Ssh with Jsch
Embed a Jre in a Windows Executable
How to Sort an Arraylist of Objects by a Property
Java 1.6: Creating an Array of List<T>
Java Converting Image to Bufferedimage
Can an Array Be Used as a Hashmap Key
How to Deploy Javafx Application, Create Jar and Self-Contained Applications and Native Installers
Jdk Dateformatter Parsing Dayofweek in German Locale, Java8 VS Java9
Retrieve Version from Maven Pom.Xml in Code
Why Does String.Valueof(Null) Throw a Nullpointerexception
Java:Why Should We Use Bigdecimal Instead of Double in the Real World
Safe String to Bigdecimal Conversion
Hiding Instance Variables of a Class
Is There a Difference Between Single and Double Quotes in Java