- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How can we change a field name in JSON using Jackson in Java?
The Jackson Annotation @JsonProperty is used on a property or method during serialization or deserialization of JSON. It takes an optional ‘name’ parameter which is useful in case the property name is different than ‘key’ name in JSON. By default, if the key name matches the property name, value is mapped to property value.
In the below example, we can change a field name in JSON using @JsonProperty annotation.
Example
import java.io.IOException; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.annotation.JsonProperty; public class JsonPropertyAnnotationTest { public static void main(String[] args) throws IOException { ObjectMapper mapper = new ObjectMapper(); mapper.enable(SerializationFeature.INDENT_OUTPUT); User user = new User("Sai", "Adithya", "9959984000", "0402358700"); String data = mapper.writeValueAsString(user); System.out.println(data); } } // User class class User { @JsonProperty("first-name") public String firstName; @JsonProperty("last-name") public String lastName; @JsonProperty("mobile-phone") public String mobilePhone; @JsonProperty("home_phone") public String workPhone; public User(String firstName, String lastName, String mobilePhone, String workPhone) { super(); this.firstName = firstName; this.lastName = lastName; this.mobilePhone = mobilePhone; this.workPhone = workPhone; } }
Output
{ "first-name" : "Sai", "last-name" : "Adithya", "mobile-phone" : "9959984000", "home_phone" : "0402358700" }
Advertisements