我收到以下错误消息,有人可以帮忙还是建议最好的调试方法。
无法从START_OBJECT中反序列化
java.lang.String
的实例 在[来源:(PushbackInputStream);行:1,列:37610] (通过参考链: com.model.ProductList [“ products”]-> java.util.ArrayList [23]-> com.model.Product [“ 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”转换为字符串。对于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;
}
答案 0 :(得分:1)
该错误表明它期望一个 VALUE (最好是 VALUE_STRING ),而它得到一个 START_OBJECT ,因此您的问题可能来自形式的json
"price": {
"was": "",
"then1": "",
"then2": "",
"now": {
...
}
"uom": "",
"currency": "GBP"
},
代替代码期望的"now": "some value"
形式。