如何将 bson 数组写入 ResponseWriter
How to Write bson Array to ResponseWriter
我正在用 GoLang 编写代码。作为其中的一部分,我通过使用 github.com/mongodb/mongo-go-driver/mongo
、github.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 结构
则需要更改
改用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)
我正在用 GoLang 编写代码。作为其中的一部分,我通过使用 github.com/mongodb/mongo-go-driver/mongo
、github.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 结构
则需要更改改用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)