Search code examples
javajsongsonobjectmapper

How to convert Object to Json String but with @JsonProperty instead of field names?


For a class similar to the following:

class A{
   @JsonProperty("hello_world")
   private String helloWorld;

   public String getHelloWorld(){...}
   public void setHelloWorld(String s){...}
}

When I try to convert it to a Json object via Obejct Mapper or GSON.

new ObjectMapper().writeValueAsString(object);
or
gson.toJson(object);

What I get is something like:

{
"helloWorld": "somevalue";
}

however I need to have the Json Property to be picked up like:

{
"hello_world": "somevalue"
}

I have looked around other similar questions, but none of them addresses this. Please help.


Solution

  • Your approach is correct while using Jackson but it won't work for Gson, as you can't mix and match @JsonProperty between these two libraries.

    If you'd like to use Jackson, then you can use @JsonProperty as shown in this example:

    public class JacksonTest {
        @Test
        void testJackson() throws JsonProcessingException {
            String json = new ObjectMapper().writeValueAsString(new A("test"));
            Assertions.assertEquals(json, "{\"test_value\":\"test\"}");
        }
    }
    class A {
        @JsonProperty("test_value")
        private final String testValue;
    
        A(String testValue) {
            this.testValue = testValue;
        }
    
        public String getTestValue() {
            return testValue;
        }
    }
    

    However, if you'd prefer using Gson in your code, you'll need to replace @JsonProperty with @SerializedName annotation, as shown here:

    public class GsonTest {
    
        @Test
        void testGson() {
            String json = new GsonBuilder().create().toJson(new B("test"));
            Assertions.assertEquals(json, "{\"test_value\":\"test\"}");
        }
    }
    class B {
        @SerializedName("test_value")
        private final String testValue;
    
        B(String testValue) {
            this.testValue = testValue;
        }
    
        public String getTestValue() {
            return testValue;
        }
    }
    

    Hope it helps.