如何使用 spring mvc + jackson 将嵌套的 json 对象发送到服务器

How to send nested json object to server using spring mvc + jackson

我有 Hotel 个实体,它有另一个名为 Location 的对象。

@Entity
public class Hotel implements Serializable {
      private static final long serialVersionUID = 1L;
      @Id
      @GeneratedValue(strategy = GenerationType.AUTO)
      private Long id;
      String name;
      @OneToOne(fetch=FetchType.LAZY)
      @JoinColumn(name="LOC_ID")
      Location location;
      //GETTER SETTER
  }

Location 像这样的对象:

@Entity
public class Location implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name="LOC_ID")
    private Long id;

    String name;

    public Location() {
    }

    public Location(String name) {
        this.name = name;
    }

    public String getName()
    {
        return name;
    }
    public void setName(String name)
    {
        this.name = name;
    }
}

我可以将 Location 对象发送到服务器 ({"name":"MyNewLoc"})。 我可以仅使用名称将酒店对象发送到服务器,这也可以 ({"name":"NewHotel"})。

但是当我尝试发送带有名称和位置属性 ({"name":"New Hotel","location":{"name":"MyNewLoc"}}) 的旅馆对象时,我收到 400 POST 错误和此响应;

exception:"org.springframework.http.converter.HttpMessageNotReadableException"

message:"Could not read JSON: Template must not be null or empty! (through reference chain: org.maskapsiz.sosyalkovan.domain.Hotel["location"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Template must not be null or empty! (through reference chain: org.maskapsiz.sosyalkovan.domain.Hotel["location"])"

我正在使用 jackson-mapper-asl 1.9.13 和 Spring 启动。

我添加了@RestResource(exported = false),它对我有用。

@Entity
@RestResource(exported = false)
public class Location implements Serializable {
}