简体   繁体   English

如何将 Object 转换为 Json String 但使用 @JsonProperty 而不是字段名称?

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

For a class similar to the following:对于类似于以下内容的 class:

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.当我尝试通过 Obejct Mapper 或 GSON 将其转换为 Json object 时。

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:但是我需要像这样拾取 Json 属性:

{
"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 object,我的代码是:

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:而 output 是:

json = { "hello_world": "laalmido" } 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.使用 Jackson 时您的方法是正确的,但它不适用于 Gson,因为您不能在这两个库之间混合和匹配@JsonProperty

If you'd like to use Jackson, then you can use @JsonProperty as shown in this example:如果您想使用 Jackson,则可以使用@JsonProperty ,如本例所示:

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:但是,如果您更喜欢在代码中使用 Gson,则需要将@JsonProperty替换为@SerializedName注释,如下所示:

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.希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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