duanping2005 2019-01-18 19:06
浏览 70
已采纳

如何将bson数组写入ResponseWriter

I am writing code in GoLang. As part of it, I generated bson array by querying a collection in MongoDB using github.com/mongodb/mongo-go-driver/mongo, github.com/mongodb/mongo-go-driver/bson. I need to write this response to http.ResponseWriter. When I attempt to do this using json.Marshal(BsonArrayReceived), response that is written to ResponseWriter has different document structure than JSON document structure stored in MongoDB. So, wanted to know the right way to write query results to ResponseWriter.

Let's say there are two documents that meet my query criteria - cat, dog

cat := bson.D{{"Animal", "Cat"}}
dog := bson.D{{"Animal", "Dog"}}

So resultant bson Array I am creating would be something like below

response := bson.A
response = append(response, cat)
response = append(response, dog)

My current code that did not work is below

writer.Header().Set("Content-Type", "application/json")    
json.err := json.Marshal(response)
writer.Write(json)

Expected output would be

[{"Animal":"Cat"},{"Animal":"Dog"}]

Actual output I receive is

[{{"Key":"Animal"},{"Value":"Cat"}},{{"Key":"Animal"},{"Value":"Dog"}}]

So my question is how do I write to ResponseWriter so I preserve the JSON document array structure. I prefer not to use custom Marshal/UnMarshal as that would mean solution is specific and need changes if I change JSON structure

  • 写回答

1条回答 默认 最新

  • dqdt45183 2019-01-21 00:32
    关注

    Use bons.M instead.

    cat := bson.M{"Animal": "Cat"}
    dog := bson.M{"Animal": "Dog"}
    response := bson.A{}
    response = append(response, cat)
    response = append(response, dog)
    writer.Header().Set("Content-Type", "application/json")
    json, _ := json.Marshal(response)
    writer.Write(json)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!