我在将JSON转换为Java对象时遇到了一个问题。
我的Json如下
{
"_id":{
"$oid":"5981428cf1aa82a313540b76"
},
"productId":1,
"name":"The Big Lebowski",
"currency":{
"currency":"USD",
"value":40.5
}
}
我正在从MongoDB数据库中检索json作为Product的DBObject。
DBObject dbObject = productsCollection.findOne(searchQuery);
if(dbObject != null)
{
Product product = (Product) AppUtils.fromDBObject(dbObject, Product.class);
return Optional.of(product);
}
产品以
返回产品[productId = 1,productName = null,currencyPrice = null]
AppUtils.java中的fromDBObject方法如下:
public static Object fromDBObject(DBObject dbObj, Class<?> clazz)
{
String json = dbObj.toString();
return new Gson().fromJson(json, clazz);
}
我的POJO如下:
public class Product
{
private long productId;
private String productName;
private CurrencyPrice currencyPrice;
// getter and setter
}
public class CurrencyPrice
{
private double value;
private String currency;
// getter and setter
}
我无法理解将json转换为Product对象的DBObject对象的位置。
谢谢!
答案 0 :(得分:1)
尝试更改您的POJO属性名称以匹配
public class Product
{
private long productId;
private String name;
private CurrencyPrice currency;
// getter and setter
}