在发送 JSON 以由 Jackson 反序列化时,似乎如果子元素的最后一个值为 ,则null
Jackson 将中止反序列化。
坏的:
如果我将此 JSON 发送到我的接收器(如下),则映射Content
对象将为null
,因为反序列化停止于image
:
{"user":{"id":"1", "token":"ABC", "image":null},"content":{"id":"2"}}
好的:
如果我这样发送它,image
仍将具有null
所需的值,但Content
将使用其 id 创建对象:
{"user":{"id":"1", "image":null, "token":"ABC"},"content":{"id":"2"}}
这对我来说就像一个错误..?!
简单的接收器:
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Transactional
public Response create(UserContent source) {
UserContent dbResult = manager.create(source);
return Response.status(200)
.entity(dbResult.getId().toString()).build();
}
串行器
public static String objectToString(Object object) {
ObjectMapper mapper = new ObjectMapper();
mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"));
Writer strWriter = new StringWriter();
try {
mapper.writeValue(strWriter, object);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
String userDataJSON = strWriter.toString();
return userDataJSON;
}
我可以将我的 ObjectMapper 设置为在发送端将所有对象序列null
化为或空对象吗?""
如果我将UserContent
具有属性的对象传递null
给上述方法,则生成的 JSON 将具有null
与上面示例类似的值,并且如果列表的最后一项具有值 null,反序列化将中止,导致我的后端出现 NullPointerExceptions。
编辑 - UserContent 类:
@Entity
@Table(name = "user_content")
@XmlRootElement
public class UserContent extends org.springframework.data.jpa.domain.AbstractPersistable<Long> {
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id", nullable = false)
@Fetch(FetchMode.JOIN)
private User user;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "content_post_id", nullable = false)
@Fetch(FetchMode.JOIN)
private Contentcontent;
// more properties...
}
我们的依赖:
<properties>
<jersey-version>1.14</jersey-version>
</properties>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.5</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>${jersey-version}</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>${jersey-version}</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-json</artifactId>
<version>${jersey-version}</version>
</dependency>
<dependency>
<groupId>com.sun.jersey.contribs</groupId>
<artifactId>jersey-multipart</artifactId>
<version>${jersey-version}</version>
</dependency>
<dependency>
<groupId>com.sun.jersey.jersey-test-framework</groupId>
<artifactId>jersey-test-framework-grizzly2</artifactId>
<version>${jersey-version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-servlet</artifactId>
<version>${jersey-version}</version>
<scope>test</scope>
</dependency>