【问题标题】:Handel JSON of different type in Spring POST request在 Spring POST 请求中处理不同类型的 JSON
【发布时间】:2014-03-16 20:08:39
【问题描述】:

尝试发布此 JSON 对象数组“抱歉格式错误”时,我不断收到错误请求 400:

{
"type":"input","uniqueId":434,"label":"name","viewToCall":"input-configuration-menu"},{"type":"button","uniqueId":930,"label":"name","viewToCall":"button-configuration-menu"}]

我不确定如何在我的@Requestbody 中处理不同类型的 json 对象:

@RequestMapping(value="/saveForm", method = RequestMethod.POST)
    public @ResponseBody void saveForm( @RequestBody ArrayList<Components> text ){
        do somthing...
    }

我找到了这个资源,但我没有经验让它在网络环境中工作: Spring @RequestBody containing a list of different types (but same interface) http://programmerbruce.blogspot.com.es/2011/05/deserialize-json-with-jackson-into.html http://aredko.blogspot.se/2012/04/json-for-polymorhic-java-object.html

【问题讨论】:

  • 您发布的 JSON 末尾有一个不匹配的 ]
  • 只是在提问的时候错过了
  • 您可能在标头中遇到内容类型问题,请显示您的请求标头

标签: json spring-mvc jackson http-post


【解决方案1】:

JSON 开头缺少 [,否则为有效 JSON。如果问题不是缺少尖括号,请将日志放在 DEBUG 或 TRACE 中,然后发布堆栈跟踪。

此外,组件需要使用类似的注释,以便 Jackson 知道需要实例化哪个对象(另请参阅 Jackson polymorphism without annotations):

@JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include=As.WRAPPER_OBJECT)
@JsonSubTypes({
    @Type(value=Input.class, value="input"), 
    @Type(value=Button.class, value="button")})
public interface Component {
    ...
}

@JsonTypeName("type")
public Sub1 implements Component {
}

@JsonTypeName("button")
public Button implements Component {
}

【讨论】:

  • 非常感谢它对我的帮助,唯一不同的是我使用了“JsonTypeInfo.As.PROPERTY”和一个抽象类。 =)
猜你喜欢
  • 2022-09-23
  • 2018-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多