BaseEntity:
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_EMPTY)
@JsonPropertyOrder({"id", "posId", "posCode", "title", "description", "sortOrder"})
public class BaseEntity {
private UUID id = UUID.randomUUID();
private String posId;
private String posCode;
private String title;
private String description;
private Integer sortOrder;
}
IntegrationCategory:
@Getter
@Setter
@NoArgsConstructor
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class IntegrationCategory extends BaseEntity {
private boolean root;
private Integer rootSortOrder;
private Collection<IntegrationSubCategoryInCategory> subCategories = new ArrayList<>();
}
IntegrationSubCategoryInCategory:
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Builder
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class IntegrationSubCategoryInCategory {
@Getter(onMethod = @__( @JsonIgnore ))
private IntegrationCategory category;
@JsonProperty(
required = true,
index = 1
)
@JsonIdentityInfo(
property = "id",
generator = ObjectIdGenerators.PropertyGenerator.class
)
@JsonIdentityReference(
alwaysAsId = true
)
private IntegrationCategory subCategory;
private Integer sortOrder;
}
此类将生成类似JSON的
"categories": [
{
"id": "8d62eb47-5491-4142-8b87-cde558165be8",
"posId": "31000",
"posCode": "31000",
"title": "Coneys",
"description": "Coneys",
"root": true,
"rootSortOrder": 1,
"subCategories": [
{
"subCategory": "72b2a181-8e76-4932-8201-56a847f95153",
"sortOrder": 1
}
]
},
{
"id": "72b2a181-8e76-4932-8201-56a847f95153",
"posId": "31100",
"posCode": "31100",
"title": "Cheese Coney",
"description": "Cheese Coney",
"root": false
},
...
序列化效果很好。当我尝试反序列化此JSON时,问题就开始了。
com.fasterxml.jackson.databind.deser.UnresolvedForwardReference: Could not resolve Object Id [72b2a181-8e76-4932-8201-56a847f95153] (for [simple type, class com.company.common.integration.protocol.digitalordering.model.IntegrationCategory]).at [Source: (StringReader); line: 1, column: 310] (through reference chain: com.company.common.integration.protocol.digitalordering.response.GetPosMenuResponse["menu"]->com.company.common.integration.protocol.digitalordering.MenuAggregator["categories"]->java.util.ArrayList[0]->com.company.common.integration.protocol.digitalordering.model.IntegrationCategory["subCategories"]->java.util.ArrayList[0]->com.company.common.integration.protocol.digitalordering.model.IntegrationSubCategoryInCategory["subCategory"])
问题似乎是杰克逊不知道类别“ Coneys”中具有“ Cheese Coneys”子类别的ID(UUID)的对象,对于Jackson来说是未知的,因为具有该UUID的类别“ Cheese Coneys”位于“类别Coneys”之下。 / p>
Jackson可以解决这种情况下的ID吗?我在做什么错了?