问题描述
因此,我有以下JSON表示想要映射到JAVA中的对象的City对象。 这是用来过滤掉不需要的字段
{
"class": [
{
"id": "default","type": [
"riskType","firstTime"
],"direction": [],"town": [
"leader",{
"streets": [
"mainStreet"
]
}
]
}
]
}
要映射它,我正在使用
ojectMapper.readValue(inputStream,new TypeReference<HashMap<String,Set<PayloadClass>>>() { });
我的有效载荷类如下:
@Data
@EqualsAndHashCode(exclude = {"town","direction","type"})
@NoArgsConstructor
public class PayloadClass {
private String id;
@NonNull private Set<String> type = Collections.emptySet();
@NonNull private Set<String> direction = Collections.emptySet();
@NonNull private Set<Town> town = Collections.emptySet();
完成我的城镇培训班是为了代表一个拥有领导者和街道的城镇
@Data
@NoArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public class Town{
@JsonProperty(value = "leader")
private String leader;
@JsonProperty(value = "streets")
private Set<String> streets = Collections.emptySet();
问题出在映射中,它试图在一个对象内映射领导者和街道集。
然后我收到以下错误,但不确定原因:
U [main] ERROR - Cannot construct instance of `
com.Town` (although at least one Creator
exists): no String-argument constructor/factory method to deserialize from String value
('leader')
at [Source: (BufferedInputStream); line: 16,column: 9] (through reference chain:
java.util.HashMap["PayloadClass"]->java.util.HashSet[0]-
com.PayloadClass["town"]->java.util.HashSet[1])
我正在尝试将JSON格式保留用于上游应用程序,希望我可以在映射类型中解决此问题。
因此,我要添加的新字段是Json中的Leader字段。没有此字段,它的执行就不会有问题。
解决方法
您的json格式错误。如果城镇是一组带有领导者和街道名称的城市对象,则应使用json编写:
{
"town": [
{
"leader": "","streets" : [
"mainStreet"
]
}
]
}