我可以访问返回 JSON 字符串的 RESTful API,如下所示:
{
"Container1": {
"active": true
},
"Container2": {
"active": false
},
}
问题在于 RESTful API 的设计有些不当。字段名称已包含数据。使用 Jackson 库,不可能将字段名称反序列化为相应 Java bean 类的属性名称。我假设,这也不是 JSON 规范的意图。上述 JSON 字符串需要反序列化为以下类的实例:
public class Container {
private Boolean active;
private String name;
}
我最终得到 UnrecognizedPropertyException
用于现场Container1
.
我想配置忽略未知属性并提供 JsonDeserializer
对于这样的属性:
@JsonIgnoreProperties(ignoreUnknown = true)
public class Container {
private Boolean active;
private String name;
@JsonDeserialize(using = FieldNameToPropertyDeserializer.class)
public void setName(String name) {
this.name = name;
}
}
和 FieldNameToPropertyDeserializer
:
public class FieldNameToPropertyDeserializer extends StdDeserializer<String> {
public FieldNameToPropertyDeserializer() {
super(String.class);
}
@Override
public String deserialize(JsonParser parser, DeserializationContext context) throws IOException, JsonProcessingException {
return parser.getCurrentName();
}
}
反序列化的调用实现如下:
String jsonString = response.readEntity(String.class);
ObjectMapper objectMapper = new ObjectMapper();
ObjectReader readerFor = objectMapper.readerFor(Container.class);
MappingIterator<Container> mappingIterator = readerFor.readValues(jsonString);
while (mappingIterator.hasNext()) {
Container container = (Container) mappingIterator.next();
containers.add(container);
}
但我只收到空对象(属性设置为 null
),因为自从我设置 @JsonIgnoreProperties(ignoreUnknown = true)
后,属性的解析被跳过了.
这可能吗?或者我应该在之后实现类似后处理的东西?
最佳答案
这个怎么样。像这样创建一个类 ContainerActive
public class ContainerActive {
private boolean active;
// constructors, setters, getters
}
你可以这样做
Map<String, ContainerActive> map = mapper.readValue(jsonString, new TypeReference<Map<String, ContainerActive>>() {});
有了这个,您将以“Container1”、“Container2”作为键,将 ContainerActive 对象作为具有 Activity 字段的值。
关于java - 如何使用 Jackson 将 JSON 字段名称转换为 Java bean 类属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58097145/