我有两种类型的项目,Java和Node js
java项目使用ObjectId
返回详细信息{
"timestamp": 1491806328,
"machineIdentifier": 9737042,
"processIdentifier": 6393,
"counter": 1399563,
"date": 1491806328000,
"time": 1491806328000,
"timeSecond": 1491806328
}
在节点Js中我使用的是Mongoose。现在我不知道如何将它解析为nodejs equalant ObjectId。
编辑:
我试过的代码,
var mongoose = require("mongoose");
var idToParse = {
"timestamp": 1491806328,
"machineIdentifier": 9737042,
"processIdentifier": 6393,
"counter": 1399563,
"date": 1491806328000,
"time": 1491806328000,
"timeSecond": 1491806328
};
mongoose.Schema.Types.ObjectId(idToParse);
它返回Undefined。
答案 0 :(得分:0)
如果您使用的是Java,请尝试使用Jackson将POJO映射到json,并为Object Id字段设置自定义序列化程序,以便Jackson知道它需要提供与ObjectId等效的String。 自定义序列化器将如下所示:
public class ObjectIdSerializer extends JsonSerializer<ObjectId>{
@Override
public void serialize(ObjectId id, JsonGenerator jgen, SerializerProvider provider)
throws IOException, JsonProcessingException {
if(id == null){
jgen.writeNull();
}else{
jgen.writeString(id.toString());
}
}}
你可以在POJO中注释ObjectId字段,如:
@Id
@JsonSerialize(using = ObjectIdSerializer.class)
private ObjectId id;
答案 1 :(得分:0)
找到答案。
function hex(length, n) {
n = n.toString(16);
return (n.length===length)? n : "00000000".substring(n.length, length) + n;
}
var idToParse = {
"timestamp": 1491806328,
"machineIdentifier": 9737042,
"processIdentifier": 6393,
"counter": 1399563,
"date": 1491806328000,
"time": 1491806328000,
"timeSecond": 1491806328
};
var idString = hex(8,idToParse.timestamp)+hex(6,idToParse.machineIdentifier)+hex(4,idToParse.processIdentifier)+hex(6,idToParse.counter);