【问题标题】:How do I serialize JSON with hyphen in key using Spring Boot?如何使用 Spring Boot 序列化带有连字符的 JSON?
【发布时间】:2019-01-01 05:37:54
【问题描述】:

我有以下 JSON...

{
    "navigation-items":[
       {
           "title":"Title",
           "description":"This is the desc",
           "link":"http://google.com"
       }
    ]
}

我有以下 Java

public class ExternalConfig {
    @SerializedName("navigation-items")
    private List<NavigationItem> items;

    public NavigationItem getNavItem(Integer index){
        return items.get(index);
    }

    public void putNavItem(NavigationItem item){
        items.add(item);
    }

    public Integer navItemSize(){
        return items == null ? 0 : items.size();
    }
}

...

@PostMapping("config")
@ResponseBody
public void setConfig(@RequestBody ExternalConfig config){
    System.out.println(config.navItemSize() > 0);
}

但是当我发送带有以下正文的请求时......

{
    "navigation-items":[
        {
            "title":"Title",
            "description":"This is the desc",
            "link":"http://google.com"
        },{
            "title":"Test 2",
            "description":"asdasdsadsadas",
            "link":"http://drudgereport.com"
        }
    ]
}

但是当我中断端点时,项目是空的。如何将带有连字符键的 JSON 传递给 Spring Boot?

【问题讨论】:

  • 如果所有属性都遵循连字符命名模式;你可以使用 PropertyNamingStrategy.KebabCaseStrategy

标签: json spring-boot serialization


【解决方案1】:

如果你使用 spring-boot,请使用 @JsonProperty。

@JsonProperty("navigation-items")
private List<NavigationItem> items;

【讨论】:

    【解决方案2】:

    这里真正的问题是我没有像这样包含 jackson-databind...

     compile 'com.fasterxml.jackson.core:jackson-databind:latest.release'
    

    不确定是否有使用 GSON 的方法,因为我已经有了,但现在我将只使用 jackson。

    【讨论】:

      猜你喜欢
      • 2019-10-03
      • 1970-01-01
      • 1970-01-01
      • 2016-05-12
      • 2018-06-02
      • 2018-09-15
      • 1970-01-01
      • 2020-01-02
      • 2020-12-15
      相关资源
      最近更新 更多