【发布时间】:2017-08-04 00:40:37
【问题描述】:
我在将 JSON 转换为 Java 对象时遇到问题。
我的 Json 如下
{
"_id":{
"$oid":"5981428cf1aa82a313540b76"
},
"productId":1,
"name":"The Big Lebowski",
"currency":{
"currency":"USD",
"value":40.5
}
}
我正在从 MongoDB 数据库中检索 json 作为产品的 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 的 DBObject 对象转换为 Product 对象的原因。
谢谢!
【问题讨论】:
-
好吧,实际上
BasicDBObject上有一个.toJson()方法,它当然与.toString(). But really you should just be using theBasicDBObject` 直接不同,因为它与AbstractMap具有相同的接口。无需强制转换为 JSON,然后再转换为对象形式。它已经是一个可用的接口,并且不是 JSON。
标签: java json mongodb rest gson