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

Time:01-17

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.

CodePudding user response:

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.

CodePudding user response:

for me it works good, I use your A object and my code is:

A a = new A();
a.setHelloWorld("laalmido");
String s = new com.fasterxml.jackson.databind.ObjectMapper().writer().withDefaultPrettyPrinter().writeValueAsString(a);
System.out.println("json = "   s);

And the output is:

json = { "hello_world" : "laalmido" }

  • Related