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)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 浏览文件夹的图库,视频,图片之类的怎样删除?
  • ¥15 怎么把512还原为520格式
  • ¥15 MATLAB的动态模态分解出现错误,以CFX非定常模拟结果为快照
  • ¥15 求高通平台Softsim调试经验
  • ¥15 canal如何实现将mysql多张表(月表)采集入库到目标表中(一张表)?
  • ¥15 wpf ScrollViewer实现冻结左侧宽度w范围内的视图
  • ¥15 栅极驱动低侧烧毁MOSFET
  • ¥30 写segy数据时出错3
  • ¥100 linux下qt运行QCefView demo报错
  • ¥50 F1C100S下的红外解码IR_RX驱动问题