问题
Im using Mongo Java driver 3.7
This is my POJO(with getters and setters) -
public class Sample{
public int field1;
public JsonNode field2;
}
Im using the below code to insert an object of Sample into MongoDB.
MongoCollection<Sample> myCollection = database.getCollection("myCollection",Sample.class);
ObjectMapper mapper = new ObjectMapper();
Sample obj = new Sample();
obj.setField1(1);
String sampleJSON = "{ \"key\": \"value\" }";
obj.setField2(mapper.readTree(sample));
myCollection.insertOne(obj);
Seen Output: (JsonNode field is empty)
{
"_id" : ObjectId("5afbff8a8f621e1e328a8c4e"),
"field1" : 1
"field2" : [
[ ]
],
}
Note: In debug mode, it is clear that the JsonNode is created with proper data. But insert is misbehaving. I guess I'm missing something here. Any leads appreciated.
Update: I tried writing a custom codec for JsonNode class, but it is never being used by mongo. This is my codec code -
@Slf4j
public class JsonNodeCodec implements CollectibleCodec<JsonNode> {
@Inject
private ObjectMapper objectMapper;
@Override
public JsonNode generateIdIfAbsentFromDocument(JsonNode jsonNode) {
return null;
}
@Override
public boolean documentHasId(JsonNode jsonNode) {
return false;
}
@Override
public BsonValue getDocumentId(JsonNode jsonNode) {
return null;
}
@Override
public JsonNode decode(BsonReader reader, DecoderContext decoderContext) {
String task = reader.readString();
JsonNode node = objectMapper.readTree(task);
return node;
}
@Override
public void encode(BsonWriter writer, JsonNode jsonNode, EncoderContext encoderContext) {
writer.writeString(jsonNode.toString());
}
@Override
public Class<JsonNode> getEncoderClass() {
return JsonNode.class;
}
}
And I'm registering the codec like this -
Codec<JsonNode> jsonNodeCodec = new JsonNodeCodec();
CodecRegistry codecRegistry = CodecRegistries.fromRegistries(com.mongodb.MongoClient.getDefaultCodecRegistry(),
CodecRegistries.fromCodecs(jsonNodeCodec),
CodecRegistries.fromProviders(PojoCodecProvider.builder().automatic(true).build())
);
PS: Other codecs registered for custom POJOs are working fine. But this codec is never being used to encode/decode JSON objects
回答1:
I was facing the same issue here and resolved using ObjectMapper.
Use below:
ObjectMapper mapper = new ObjectMapper();
Map inputMap = mapper.convertValue(jsonNode, Map.class);
来源:https://stackoverflow.com/questions/50368001/inserting-a-pojo-with-a-jsonnode-field-into-mongodb-using-java-driver