java 将Jackson与Spring Data MongoDB一起使用

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 将Jackson与Spring Data MongoDB一起使用相关的知识,希望对你有一定的参考价值。

package cz.blindspot.armorway.analytics.configuration;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.TreeNode;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.mongodb.*;
import com.mongodb.util.JSON;
import org.bson.types.ObjectId;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
import org.springframework.data.mongodb.core.convert.DbRefResolver;
import org.springframework.data.mongodb.core.convert.DefaultDbRefResolver;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;

import java.io.IOException;
import java.util.Collections;
import java.util.List;

import static com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES;

@Configuration
@PropertySource(value = "classpath:mongodb.properties")
public class MongoConfiguration extends AbstractMongoConfiguration {

    @Value("${mongodb.host}")
    private String host;

    @Value("${mongodb.db}")
    private String databaseName;

    @Value("${mongodb.port}")
    private int port;

    @Value("${mongodb.user}")
    private String user;

    @Value("${mongodb.passwd}")
    private String passwd;


    @Override
    protected String getDatabaseName() {
        return databaseName;
    }

    @Override
    public Mongo mongo() throws Exception {
        ServerAddress serverAddress = new ServerAddress(host, port);
        List<MongoCredential> credentials = Collections.singletonList(
                MongoCredential.createCredential(user, databaseName, passwd.toCharArray())
        );

        MongoClient mongoClient = new MongoClient(serverAddress, credentials);
        return mongoClient;
    }

    @Override
    public MappingMongoConverter mappingMongoConverter() throws Exception {
        DbRefResolver dbRefResolver = new DefaultDbRefResolver(mongoDbFactory());
        ObjectMapper mapper = new ObjectMapper()
                .configure(FAIL_ON_UNKNOWN_PROPERTIES, false)
                .registerModule(new SimpleModule() {
                    {
                        addDeserializer(ObjectId.class, new JsonDeserializer<ObjectId>() {
                            @Override
                            public ObjectId deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
                                TreeNode oid = p.readValueAsTree().get("$oid");
                                String string = oid.toString().replaceAll("\"", "");

                                return new ObjectId(string);
                            }
                        });
                    }
                });


        MappingMongoConverter converter = new MappingMongoConverter(dbRefResolver, mongoMappingContext()) {
            @Override
            public <S> S read(Class<S> clazz, DBObject dbo) {
                String string = JSON.serialize(dbo);
                try {
                    return mapper.readValue(string, clazz);
                } catch (IOException e) {
                    throw new RuntimeException(string, e);
                }
            }

            @Override
            public void write(Object obj, DBObject dbo) {
                String string = null;
                try {
                    string = mapper.writeValueAsString(obj);
                } catch (JsonProcessingException e) {
                    throw new RuntimeException(string, e);
                }
                dbo.putAll((DBObject) JSON.parse(string));
            }
        };

        return converter;
    }

    @Bean
    @NotNull
    public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
        return new PropertySourcesPlaceholderConfigurer();
    }
}

以上是关于java 将Jackson与Spring Data MongoDB一起使用的主要内容,如果未能解决你的问题,请参考以下文章

使用 Jackson Annotation 将 json 数据映射到 Spring Data JPA 中的预期值

Spring Boot 2. Jackson json 序列化或 Spring Data JPA FetchType.Lazy

Neo4j 和 Spring-data Map 查询结果到 Jackson JsonNode

如何正确地在Spring Data JPA和Jackson中用上Java 8的时间相关API(即JSR 310也即java.time包下的众神器)

Java/Spring/Jackson 驼峰-下划线字段转换

Spring Data Mongo + 延迟加载 + REST Jackson