2017-04-13 48 views
0

解析對象ID有兩種類型的項目,Java和節點JS我如何從對象

Java項目用的ObjectId

{ 
     "timestamp": 1491806328, 
     "machineIdentifier": 9737042, 
     "processIdentifier": 6393, 
     "counter": 1399563, 
     "date": 1491806328000, 
     "time": 1491806328000, 
     "timeSecond": 1491806328 
    } 

返回的細節在節點的js我使用的貓鼬。現在我不知道如何解析這個到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

您試過的代碼在哪裏? :-) – bestprogrammerintheworld

+0

問題尋求幫助調試(「爲什麼不是這個代碼的工作?」)必須包括所期望的行爲,一個特定的問題或錯誤,並重現它在問題本身所需要的最短的代碼。沒有明確問題陳述的問題對其他讀者無益。請參閱:https://stackoverflow.com/help/how-to-ask –

+0

先生,@AustinKootz感謝您的建議。現在編輯代碼。請立即檢查 –

回答

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

如果您正在使用Java,試圖利用傑克遜的映射POJO以JSON和有對象ID字段自定義序列,使傑克遜的理解是,需要給字符串等同的ObjectId的。 自定義序列化將是這樣的:

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(使用= ObjectIdSerializer.class)
私人的ObjectId ID;

+0

謝謝。 @Vaishnavi,不幸的是,Java部分是一個外部派對。所以我必須做的JavaScript代。最後我得到了代碼。謝謝 –