当前位置: 首页 > 知识库问答 >
问题:

使用Jongo和Jackson2,如何将MongoDB ObjectId(在POJO中的String_id下表示)反序列化为十六进制字符串表示?

穆丁雨
2023-03-14

我在pom.xml中使用的依赖关系:

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>

        ...

        <jersey.container.version>2.13</jersey.container.version>
        <jackson.version>2.4.3</jackson.version>
        <genson.version>1.1</genson.version>        
        <jongo.version>1.1</jongo.version>
    </properties>

  <dependencies>

     ...

    <dependency>
        <groupId>org.glassfish.jersey.containers</groupId>
        <artifactId>jersey-container-servlet</artifactId>
        <version>${jersey.container.version}</version>
    </dependency>

    <dependency>
        <groupId>org.glassfish.jersey.media</groupId>
        <artifactId>jersey-media-json-jackson</artifactId>
        <version>${jersey.container.version}</version>
    </dependency>

    <!-- Required only when you are using JAX-RS Client -->
    <dependency>
        <groupId>org.glassfish.jersey.core</groupId>
        <artifactId>jersey-client</artifactId>
        <version>${jersey.container.version}</version>
    </dependency>

    <dependency>
        <groupId>javax.ws.rs</groupId>
        <artifactId>javax.ws.rs-api</artifactId>
        <version>2.0.1</version>
    </dependency>

    <dependency>
        <groupId>org.glassfish.jersey.media</groupId>
        <artifactId>jersey-media-multipart</artifactId>
        <version>2.13</version>
    </dependency>

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>${jackson.version}</version>
    </dependency>

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>${jackson.version}</version>
    </dependency>

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>${jackson.version}</version>
    </dependency>

    <dependency>
        <groupId>org.jongo</groupId>
        <artifactId>jongo</artifactId>
        <version>${jongo.version}</version>
    </dependency>

    <dependency>
        <groupId>org.mongodb</groupId>
        <artifactId>mongo-java-driver</artifactId>
        <version>2.12.3</version>
    </dependency>
  </dependencies>

我的用户POJO:

import com.google.common.base.MoreObjects;

import java.util.Objects;

import org.jongo.marshall.jackson.oid.Id;
import org.jongo.marshall.jackson.oid.ObjectId;


public class User {

    @Id 
    @ObjectId
    private String _id;

    private String firstName;

    private String lastName;

    private int age;

    // Must have no-argument constructor
    public User() {

    }

    public User(String _id, String firstName, String lastName, int age) {
        this._id = _id;
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
    }

    public String get_id() {
        return _id;
    }

    public void set_id(String _id) {
        this._id = _id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override 
    public int hashCode() {
         return Objects.hash(_id, firstName, lastName, age);
     }

    @Override
    public boolean equals(final Object obj) {
        if (this == obj) {
            return true;
        }

        if (obj == null || getClass() != obj.getClass()) {
            return false;
        }

        final User other = (User) obj;

        return Objects.equals(_id, other._id) &&
               Objects.equals(firstName, other.firstName) && 
               Objects.equals(lastName, other.lastName) &&
               Objects.equals(age, other.age);
    }

    @Override
    public String toString() {
        return MoreObjects.toStringHelper(this)
                         .add("firstName", firstName)
                         .add("lastName", lastName)
                         .add("age", age)
                         .add("_id", _id)
                         .toString();
    }
}

我的web服务:

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import com.hive5.dao.UsersDAO;
import com.hive5.enums.CustomHttpResponse;
import com.hive5.pojo.User;

@Path("/v1")
public class V1_Users {

    @GET
    @Path("/users/{firstName}")
    @Produces(MediaType.APPLICATION_JSON)
    public Response getUser(@PathParam("firstName") String firstName) {
        if (firstName != null && !firstName.trim().isEmpty()) {
            Response response = UsersDAO.getUser(firstName);
            return response;
        } else {
            return Response
                    .status(CustomHttpResponse.REQUEST_NOT_ACCEPTABLE
                            .getStatusCode())
                    .entity(CustomHttpResponse.REQUEST_NOT_ACCEPTABLE
                            .getStatusMessage()).build();
        }
    }

    ...

}
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.ws.rs.core.Response;

import org.apache.log4j.Logger;
import org.bson.types.ObjectId;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hive5.enums.CustomHttpResponse;
import com.hive5.pojo.User;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.MongoException;

public class UsersDAO {

    ...

    public static Response getUser(String firstName) {
        DB db = MONGO_CLIENT.getDB(DATABASE_NAME);
        DBCollection collection = db.getCollection("users");
        BasicDBObject whereQuery = new BasicDBObject();
        whereQuery.put("firstName", firstName);

        DBCursor cursor = null;
        DBObject dbObject = null;
        User user = null;

        ObjectMapper mapper = new ObjectMapper();

        CustomHttpResponse customHttpResponse = CustomHttpResponse.OK;

        try {
            cursor = collection.find(whereQuery).limit(1);
            if (cursor.count() > 0) {
                dbObject = cursor.next();
                user = mapper.readValue(dbObject.toString(), User.class);
            } else {
                // User Not Found
                customHttpResponse = CustomHttpResponse.NOT_FOUND_CUSTOM;
                customHttpResponse
                        .formatStatusMessagePatternWithArguments(firstName);
            }
        } catch (MongoException | IOException e) {
            customHttpResponse = CustomHttpResponse.INTERNAL_SERVER_ERROR;
            LOG_TO_CONSOLE.fatal(e, e);
            LOG_TO_FILE.fatal(e, e);
        } finally {
            if (customHttpResponse == CustomHttpResponse.OK
                    || customHttpResponse == CustomHttpResponse.NOT_FOUND_CUSTOM) {
                LOG_TO_CONSOLE.debug(customHttpResponse.toString());
            }
        }

        Response response = null;
        switch (customHttpResponse) {
        case OK:

            System.out.println("user.get_id() -> " + user.get_id());

            response = Response.status(customHttpResponse.getStatusCode())
                    .entity(user).build();
            break;
        default:
            response = Response.status(customHttpResponse.getStatusCode())
                    .entity(customHttpResponse.getStatusMessage()).build();
            break;
        }

        return response;
    }

    ...
}
user.get_id() -> 54452976a826c51b864dd2e9
{
    "firstName": "Yolo",
    "lastName": "DOUCE",
    "age": 31,
    "_id": {
        "new": false,
        "inc": -2041720087,
        "machine": -1473854181,
        "timeSecond": 1413818742,
        "timestamp": 1413818742,
        "time": 1413818742000,
        "date": 1413818742000
    }
}

共有1个答案

娄建义
2023-03-14

ObjectIdSerializer总是将用@Objectid映射的属性写入Objectid的新实例。当您将此属性映射到字符串时,这是错误的。

为了避免这种行为,我们可以使用以下自定义JSON序列化器类(最初由某个user1878815提供)NoObjectIdSerializer,我对其进行了一点修改:

import java.io.IOException;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

public class NoObjectIdSerializer extends JsonSerializer<String> {

    @Override
    public void serialize(String value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
        if(value == null){
            jgen.writeNull();
        }else{
            jgen.writeString(value);
        }
    }

}

像这样使用:

import org.jongo.marshall.jackson.oid.ObjectId;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.mypackage.NoObjectIdSerializer;

import com.google.common.base.MoreObjects;
import java.util.Objects;

public class User {

   @ObjectId
   @JsonSerialize(using = NoObjectIdSerializer.class)
   protected final String _id;

   ...
}
 类似资料: