Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
"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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading