Using Jongo and Jackson 2, how to deserialize a MongoDB ObjectId (represented under String _id in a POJO) to an hexadecimal String representation?

旧时模样 提交于 2021-02-07 08:43:23

问题


I use the latest version of MongoDB database and the latest version of the official JAVA MongoDB driver.

The dependencies that I use in my 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>

My User 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();
    }
}

My web service:

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();
        }
    }

    ...

}

My DAO:

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;
    }

    ...
}

The ouput displayed in the console of my tomcat web server (after having requested the web service above, see my DAO class and getUser(String firstName) {...} method above):

user.get_id() -> 54452976a826c51b864dd2e9

The JSON result that I get after having requested the web service using POSTMAN:

{
    "firstName": "Yolo",
    "lastName": "DOUCE",
    "age": 31,
    "_id": {
        "new": false,
        "inc": -2041720087,
        "machine": -1473854181,
        "timeSecond": 1413818742,
        "timestamp": 1413818742,
        "time": 1413818742000,
        "date": 1413818742000
    }
}

As you can see the _id field is not under an hexadecimal string format but instead it has multiple fields, this is not what I expect.

1 - Actually in my DAO I am able to print the hexadecimal string format for this field, so I do not understand why in my web service it returns a response which apparently contains an Object representation of the String _id?

2 - My second question is to know in my particular case, how to deserialize to JSON and return an hexadecimal String representation of String _id (field located in my User POJO), using jongo and/or jackson faster xml V2 and MongoDB?


回答1:


ObjectIdSerializer always writes property mapped with @ObjectId to a new instance of ObjectId. This is wrong when you map this property to a String.

To avoid this behaviour, we can use this following custom JSON Serializer class (initially provided by a certain user1878815) NoObjectIdSerializer that I have a little bit modified:

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);
        }
    }

}

Used like this:

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;

   ...
}

There is an open issue here.

This answer is based on a previous answer provided by user1878815, a lot of thanks to him.

Also for a more detailed explanation, please follow this link.



来源:https://stackoverflow.com/questions/26474514/using-jongo-and-jackson-2-how-to-deserialize-a-mongodb-objectid-represented-un

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!