我有一个带有 HTTPS 的 Spring Boot/Spring MVC 网站。在我的页面上,我使用基本的 AJAX 调用来获取由 @RestController 提供的 JSON 数据,但它似乎被截断或我不完全理解。

当我单独调用 REST 端点时,我得到了全屏输出——它是我使用 Jackson 序列化的 POJO 列表。当我通过 ajax 调用它时,它会被截断或者其他什么。

当我将其发送到控制台以查看我得到的内容时:

console.log("now returning this:");  //shows 'now returning this'. 
console.log(response); //returns Array [ Object, 13, 15, 19 ] 

响应中的第一件事始终是一个对象,但如果超过 1 个,那么我将获得一个数字列表,这些数字似乎指向 @JsonIdentityInfo 生成的 ID。

所以 pojo 看起来有点像这样:

@JsonIdentity(generator = ObjectIdGenerators.IntSequenceGenerator.class, property="@id") 
@Entity 
@Table (name = "tablename") 
@JsonIgnoreProperties(ignoreUnknown = true) //because Jackson keeps throwing in new stuff 
public class Table { 
    @Id 
    @GeneratedValue(strategy=GenerationType.AUTO) 
    @Column(name = "columnname") 
    private Long id; 
 
    .....lots of properties and gets/sets 
 
    @ManyToOne 
    @JoinColumn(name = "col2", referencedColumnName = "col2", nullable = false, insertable = false, updatable = false) 
    @JsonBackReference(value = "blah") 
    @JsonIgnore 
    private OtherObject obj; 
 
    ....more gets and sets.  The OtherObject class has the ManagedReference.... 
} 

在我的 JavaScript 中:

$.ajax({ 
   url: "../mytesturl/" + ID, 
   dataType: "json", 
   contentType: "application/json", 
   timeout: 1000000 
}).done(function (response) { 
   console.log("now returning this:");  //shows 'now returning this'. 
   console.log(response); //returns Array [ Object, 13, 15, 19 ] 
}); 

我的 RestController 非常基本(只有很多行):

@RestController 
public class RestController { 
   @RequestMapping(path = "mytesturl/{id}", method = RequestMethod.GET, produces = "application/json") 
   public String getById(@PathVariable("id") Long id) throws JsonProcessingException { 
      List<Objects> list = dao.findAllById(id); 
      return objectMapper.writeValueAsString(list); 
   } 
} 

当我通过使用浏览器调用 REST 调用来检查它的结果时,我得到了一个包含所有引用和反向引用等内容的完整列表。伟大的。似乎一切都在那里。

当我进行 ajax 调用时,我得到 Array[Object, 1, 2, 3]。

我四处寻找,认为这可能是一个奇怪的解析问题,或者可能是截断。我有

server.compression.enabled = true 

所以我猜它正在压缩(使用内部 Tomcat)。

有人有什么想法吗?我不记得在使用 Gson 时遇到过这个问题,而且我可以清楚地看到 Jackson 放入了一堆“有用”的额外字段,因此我可以看到可能需要一些压缩设置或增加某种缓冲区限制。

请您参考如下方法:

在你的ajax函数中尝试使用完成

console.log(JSON.stringify(response)); 

并在您的休息 Controller 中返回一个对象列表(这对我有用,我曾经返回一个像 List<Car> 这样的对象列表):

@RestController 
public class RestController { 
   @RequestMapping(path = "mytesturl/{id}", method = RequestMethod.GET, produces = "application/json") 
   public List<Objects> getById(@PathVariable("id") Long id) throws JsonProcessingException { 
      List<Objects> list = dao.findAllById(id); 
      return list ; 
   } 
} 


评论关闭
IT源码网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!