如何将对象转换为Json字符串,但与@JsonProperty而不是字段名?



对于类似于以下的类:

class A{
@JsonProperty("hello_world")
private String helloWorld;
public String getHelloWorld(){...}
public void setHelloWorld(String s){...}
}

当我试图通过对象映射器或GSON将其转换为Json对象时。

new ObjectMapper().writeValueAsString(object);
or
gson.toJson(object);
我得到的结果是:
{
"helloWorld": "somevalue";
}

然而,我需要有Json属性被拾取,如:

{
"hello_world": "somevalue"
}

我看过其他类似的问题,但没有一个解决这个问题。请帮助。

您的方法在使用Jackson时是正确的,但它不适用于Gson,因为您不能在这两个库之间混合和匹配@JsonProperty

如果您想使用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;
}
}

但是,如果您希望在代码中使用Gson,则需要用@SerializedName注释替换@JsonProperty,如下所示:

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

希望有帮助。

对我来说它工作得很好,我使用你的A对象和我的代码是:

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

输出为:

json = {"hello_world":";laalmido"}

最新更新