JSON 键名中带有破折号的响应

JSON response with dash in the key-name

我正在使用 feign 进行休息通话。不幸的是,我收到的回复之一看起来像这样:

{
    "customer-id" : "0123"
}

JSON 响应自动映射到我的一个 POJO。此响应对象不能有名称为 "customer-id" 的 属性 字段,因为标识符的名称中不允许使用破折号 (-)。

我尝试了以下方法:

public class LookUpAccountsResponse {
        @JsonProperty("customer-id")
        private String customerId;
}

但不幸的是,这不起作用。有人对如何解决这个问题有建议吗?

它工作正常。这是一个最小的例子:

  public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
    SomeClass sc = new ObjectMapper().readValue("{\"property-with-dash\": 5}", SomeClass.class);

    System.out.println(sc.propertyWithDash);
  }

  public static class SomeClass {
    @JsonProperty("property-with-dash")
    private int propertyWithDash;
  }

这会按预期打印 5。没有投诉。

com.google.gson.GsonDecoder

不确定为什么 JsonProperty 在您的类路径中,但请参阅 "field naming support" https://github.com/google/gson/blob/master/UserGuide.md#json-field-naming-support

@SerializedName 是您需要的 Gson 注释

或者完全切换到使用 feign-jackson 依赖项和 JacksonDecoder

使用 JsonObjects 和 JsonArrays 将允许您获取字符串形式的键和值

您可以使用@JsonAlias。

它为反序列化期间接受的 属性 定义了一个或多个替代名称,即将 JSON 数据设置为 Java 对象。

@JsonAlias("customer-id")

私人字符串 customerId;