java-使用Jongo和Jackson 2,如何将MongoDB ObjectId(在POJO中的String _id下表示)反序列化为十六进制String表示形式?
作者:互联网
我使用最新版本的MongoDB数据库和最新版本的官方JAVA MongoDB驱动程序.
我在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();
}
}
我的网络服务:
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();
}
}
...
}
我的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;
}
...
}
显示在我的tomcat Web服务器控制台中的输出(在请求了上面的Web服务之后,请参见我的DAO类和上面的getUser(String firstName){…}方法):
user.get_id() -> 54452976a826c51b864dd2e9
使用POSTMAN请求Web服务后获得的JSON结果:
{
"firstName": "Yolo",
"lastName": "DOUCE",
"age": 31,
"_id": {
"new": false,
"inc": -2041720087,
"machine": -1473854181,
"timeSecond": 1413818742,
"timestamp": 1413818742,
"time": 1413818742000,
"date": 1413818742000
}
}
如您所见,_id字段不是十六进制字符串格式,而是具有多个字段,这不是我期望的.
1-实际上,在我的DAO中,我能够打印此字段的十六进制字符串格式,所以我不明白为什么在我的Web服务中它返回一个显然包含String _id的Object表示的响应?
2-我的第二个问题是在我的特定情况下,如何使用jongo和/或jackson更快的xml V2和MongoDB,如何反序列化为JSON并返回String _id(位于用户POJO中的字段)的十六进制String表示形式?
解决方法:
ObjectIdSerializer总是将与@ObjectId映射的属性写入新的ObjectId实例.当您将此属性映射到字符串时,这是错误的.
为了避免这种行为,我们可以使用下面的自定义JSON Serializer类(最初由某个用户1878815提供),我对此做了一些修改:
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;
...
}
该答案是基于user1878815提供的先前答案,非常感谢他.
另外,有关更详细的说明,请遵循此link.
标签:mongodb,jackson,jersey-2-0,jongo,java 来源: https://codeday.me/bug/20191029/1956945.html