简体   繁体   中英

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.

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" }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM