1 回答
TA贡献1898条经验 获得超8个赞
该解决方案背后的想法是实现一个特定的解串器。
public class ProductDeserializer extends StdDeserializer<Product> {
public ProductDeserializer() {
super(Product.class);
}
@Override
public Product deserialize(JsonParser parser, DeserializationContext ctxt) throws IOException {
Product p = new Product();
while (parser.nextToken() != JsonToken.END_OBJECT) {
String tokenName = parser.getCurrentName();
switch (tokenName) {
case "id":
parser.nextToken();
p.setId(parser.getText());
break;
// when you encounter an attribute called value or "" you take its value
case "value":
case "":
parser.nextToken();
p.setValue(parser.getText().trim());
break;
default:
break;
}
}
return p;
}
}
当你使用该类时,你必须注册它XmlMapper:
XmlMapper xmlMapper = new XmlMapper();
SimpleModule module = new SimpleModule("configModule", Version.unknownVersion());
module.addDeserializer(Product.class, new ProductDeserializer());
xmlMapper.registerModule(module)
产品 POJO 具有 id 和 value 作为属性。
添加回答
举报