我有以下Address和AddressList类
difftime
然后是一个Person类
public class Address {
private String street;
private String city;
private String state;
// ...
}
public class AddressList {
private List<Address> addresses;
// ...
}
然后我有像这样的Yaml文件
public class Person {
private String name;
@JsonDeserialize(contentUsing = ListDeserializer.class)
private Map<String, AddressList> addresses;
// ..
}
My List反序列化程序类如下:
---
name: 'abc'
addresses:
offices:
- street: 123 main st
city: san francisco
state: ca
- street: 234 post st
city: san francisco
state: ca
} 我的解析代码如下:
public class ListDeserializer extends JsonDeserializer<AddressList> {
@Override
public AddressList deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
return jsonParser.readValueAs(new TypeReference<Map<String, List<Address>>>() {
});
}
当我读取地址列表时:它打印为
ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory());
return objectMapper.readValue(inputYamlFile, Person.class);
任何人都可以帮忙解决这个问题吗?
答案 0 :(得分:0)
如果它被序列化为列表,则必须以相同的方式对其进行反序列化。但是你有了列表,并且可以自己迭代。
答案 1 :(得分:0)
我找到了一种方法来解决此问题,使用转换器反序列化地址映射。
我所做的修改是
public class Person {
private String name;
@JsonDeserialize(converter = AddressListConverter.class)
private Map<String, AddressList> addresses;
// ..
}
然后,我为AddressList写了一个新的转换器类。
public class AddressListConverter implements Converter<Map<String, List<LinkedHashMap>>, Map<String, AddressList>> {
@Override
public Map<String, AddressList> convert(Map<String, List<LinkedHashMap>> stringListMap) {
Map<String, AddressList> addressListMap = new HashMap<>();
ObjectMapper mapper = new ObjectMapper();
for (Map.Entry<String, List<LinkedHashMap>> entry : stringListMap.entrySet()) {
AddressList addressList = new AddressList();
for(LinkedHashMap map: entry.getValue()) {
Address address = mapper.convert(map, Address.class);
addressList.getAddresses().add(address);
}
addressListMap.put(entry.getKey(), addressList);
}
return addressListMap;
}
@Override
public JavaType getInputType(TypeFactory typeFactory) {
return typeFactory.constructMapType(Map.class, String.class, List.class);
}
@Override
public JavaType getOutputType(TypeFactory typeFactory) {
return typeFactory.constructMapType(Map.class, String.class, AddressList.class);
}
}
这应该可以解决问题