我收到以下错误消息,有人能帮忙或建议如何最好地调试它吗。
无法从START_OBECT中反序列化
java.lang.String
的实例[源:(PushbackInputStream);行:1,列:37610]处的令牌(通过参考链:com.model.ProductList["products"]->java.util.ArrayList[23]->com.model.Poduct["price"]->com.price["now"])
我正在尝试从REst API调用取消对Products对象的序列化。代码一直运行良好,直到我添加了代码来取消Price子类的序列化。如下所示,
"price": {
"was": "",
"then1": "",
"then2": "",
"now": "59.00",
"uom": "",
"currency": "GBP"
},
我的价格pojo看起来如下,
public class Price {
@JsonProperty("was")
String was;
@JsonProperty("then1")
String then1;
@JsonProperty("then2")
String then2;
@JsonProperty("now")
String now;
@JsonProperty("uom")
String uom;
@JsonProperty("currency")
String currency;
public Price() {
//blank constructor for JSON
}
@Override
public String toString() {
return "Price{" +
"was='" + was + ''' +
", then1='" + then1 + ''' +
", then2='" + then2 + ''' +
", now='" + now + ''' +
", uom='" + uom + ''' +
", currency='" + currency + ''' +
'}';
}
}
我写了一个Junit测试来尝试模拟错误,但它在我的测试中有效
@Test
public void shouldConvertJsonProductListIntoPrice() {
ObjectMapper objectMapper = new ObjectMapper();
String content3 = "{"products": [{"productId": "3525085","title": "hush Tasha Vest Dress", " +
""price": {"was": "","then1": "","then2": "","now": "59.00","uom": "","currency": "GBP"}, " +
""colorSwatches": [{"basicColor": "Red","skuId": "237494589"},{"basicColor": "Blue","skuId": "237494562"}] " +
"}]}";
JavaType valueType = objectMapper.constructType(ProductList.class);
ProductList readValue;
try {
readValue = objectMapper.readValue(content3, valueType);
assertEquals("3525085", readValue.getProductList().get(0).productId);
assertEquals("hush Tasha Vest Dress", readValue.getProductList().get(0).title);
assertEquals("", readValue.getProductList().get(0).price.then1);
assertEquals("59.00", readValue.getProductList().get(0).price.now);
assertEquals("Blue", readValue.getProductList().get(0).colorSwatches[1].basicColor);
assertEquals("237494562", readValue.getProductList().get(0).colorSwatches[1].skuId);
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
如果我注释掉了"now"字段,那么我的RestAPI调用工作得很好,我看不到异常所以"now"字段似乎有问题,我注意到它试图将"59.00"转换为String。这可能是Fasterxml转换器的问题吗?也许我需要帮忙吗?
Product类如下所示(尽管这是我从API调用中接收的字段列表,数量减少了很多)。
public class Product {
@JsonProperty("productId")
String productId;
@JsonProperty("title")
String title;
@JsonProperty("colorSwatches")
ColorSwatch [] colorSwatches;
@JsonProperty("price")
Price price;
public Product(){
// blank required for Jackson
}
public Product(String productId, String title, ColorSwatch[] colorSwatches, Price price){
this.productId = productId;
this.title = title;
this.colorSwatches = colorSwatches;
this.price = price;
}
该错误表示它需要一个VALUE(最好是VALUE_STRING),而它得到的是START_OBJECT,因此您的问题可能来自形式的json
"price": {
"was": "",
"then1": "",
"then2": "",
"now": {
...
}
"uom": "",
"currency": "GBP"
},
而不是代码所期望的"now": "some value"
形式。