我创建了这个自定义转换器:
@Component
@WritingConverter
public class MetadataWriterConverter implements Converter<Metadata, DBObject> {
@Override
public DBObject convert(Metadata metadata) {
DBObject dbObject = new BasicDBObject();
dbObject.put("name", metadata.getName());
dbObject.put("metadata", (BasicDBObject) BasicDBObject.parse(reference.getMetadata()));
dbObject.removeField("_class");
return dbObject;
}
}
我遇到此异常:
由以下原因引起:org.bson.BsonInvalidOperationException:仅在CurrentBSONType为DOCUMENT时才能调用readStartDocument,而在CurrentBSONType为ARRAY时不能调用。
问题出在
(BasicDBObject) BasicDBObject.parse(metadata.getMetadata())
metadata.getMetadata
的内容是:"[{'departament': 'JUST'}]"
。
Metadata
类是:
public class Metadata {
private String id;
private String user;
private String metadata;
}
metadata
字段的内容是一个json字符串,我正尝试转换为BasicDbObject
,但是当此字符串是json数组:[{},{}]
时出现问题。
猜猜:
Metadata met = new Metadata();
met.setId("Mdt1");
met.setUser("user");
met.setMetadata("[{'departament': 'JUST'}]");
我想要得到的是:
{
"id": Mdt1,
"user": "user",
"metadata": [{"departament": "JUST"}]
}
关于如何重构转换器的任何想法?
答案 0 :(得分:0)
实际上,BasicDBObject.parse()
期望在示例中传递的是JSONObject
而不是JSONArray
。在此处检查文档-http://api.mongodb.com/java/current/com/mongodb/BasicDBObject.html#parse-java.lang.String-
相反,您可以尝试将reference.getMetadata()
转换为valid JSON String
,然后将BasicDBList
用于JSONArray
。如下所示:
@Component
@WritingConverter
public class MetadataWriterConverter implements Converter<Metadata, DBObject>
{
@Override
public DBObject convert(Metadata metadata) {
DBObject dbObject = new BasicDBObject();
dbObject.put("name", metadata.getName());
String jsonString = String.format("{\"data\": " + reference.getMetadata() + "}");
BasicDBObject basicDBObject = (BasicDBObject) BasicDBObject.parse(jsonString);
BasicDBList parsedList = (BasicDBList) basicDBObject.get("data");
dbObject.put("metadata", parsedList);
dbObject.removeField("_class");
return dbObject;
}
}