【问题标题】:How to Write bson Array to ResponseWriter如何将 bson 数组写入 ResponseWriter
【发布时间】:2019-01-21 08:32:01
【问题描述】:

我正在用 GoLang 编写代码。作为其中的一部分,我通过使用github.com/mongodb/mongo-go-driver/mongogithub.com/mongodb/mongo-go-driver/bson 在 MongoDB 中查询一个集合来生成 bson 数组。我需要将此响应写给 http.ResponseWriter。当我尝试使用json.Marshal(BsonArrayReceived) 执行此操作时,写入 ResponseWriter 的响应具有与存储在 MongoDB 中的 JSON 文档结构不同的文档结构。因此,想知道将查询结果写入 ResponseWriter 的正确方法。

假设有两个文档符合我的查询条件——猫、狗

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

所以我创建的结果 bson 数组将如下所示

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

我当前不起作用的代码如下

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

预期的输出是

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

我收到的实际输出是

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

所以我的问题是如何写入 ResponseWriter 以便保留 JSON 文档数组结构。我不喜欢使用自定义 Marshal/UnMarshal,因为这意味着解决方案是特定的,并且如果我更改 JSON 结构则需要更改

【问题讨论】:

  • 定义一个结构并在字段上放置适当的jsonbson标签。
  • 您是否建议使用 type jsonArrayResp struct {Type string bson:"Animal" json:"Animal"}。如果是这样,当我的新回复是 {"Non-Living": {"Stone":"Marble"}} 时,我会遇到问题。那么是否有任何通用方法可以将 bson.A 转换为 []byte

标签: mongodb go deserialization bson


【解决方案1】:

请改用bons.M

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-07
    • 2021-11-26
    • 2021-03-05
    • 2017-08-31
    • 2016-05-17
    • 2011-03-16
    相关资源
    最近更新 更多