2017-11-30 11 views
0

후 내 DB를 형성하고 시도하고 나는 몇 가지 문제로 실행 JSON으로 그것을 렌더링 :ObjectID를 사용하여 bson.MarshalJSON (myStruct)을 올바르게 작성하는 방법은 무엇입니까? 내가 잡아 촬영하면

type PostBSON struct { 
    Id  bson.ObjectId `bson:"_id,omitempty"` 
    Title string  `bson:"title"` 
} 

// ... 

postBSON := PostBSON{} 
id := bson.ObjectIdHex(postJSON.Id) 
err = c.Find(bson.M{"_id": id}).One(&postBSON) 

// ... 

response, err := bson.MarshalJSON(postBSON) 

MarshalJSON 나를 위해 Id (ObjectId가)를 hexing 처리하지 않습니다. 따라서 얻을 수 있습니다 :

{"Id":{"$oid":"5a1f65646d4864a967028cce"}, "Title": "blah"} 

출력을 정리하는 올바른 방법은 무엇입니까?

{"Id":"5a1f65646d4864a967028cce", "Title": "blah"} 

편집

: 나는 내 자신의 캐릭터 라인 화 as described here을 썼다. 실적이 좋은 솔루션입니까? 그리고 그것은 바보 같은가요?

func (p PostBSON) String() string { 
    return fmt.Sprintf(` 
     { 
      "_id": "%s", 
      "title": "%s", 
      "content": "%s", 
      "created": "%s" 
     }`, 
    p.Id.Hex(), 
    p.Title, 
    p.Content, 
    p.Id.Time(), 
) 

답변

2

당신은 json.Marshaler 인터페이스, 예컨대 :

func (a PostBSON) MarshalJSON() ([]byte, error) { 
    m := map[string]interface{}{ 
     "id": a.Id.Hex(), 
     "title": a.Title, 
    } 
    return json.Marshal(m) 
} 
을 만족하는 MarshalJSON을 구현할 수 있습니다