网页API返回扩展键 - 值对象,而不是原来的JSON对象 [英] Web Api returns expanded key-value object instead of original JSON object

查看:269
本文介绍了网页API返回扩展键 - 值对象,而不是原来的JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我送 {名:李四,时代:18日,国:USA} 与我的C#的Web API POST API /测试,我把它保存在我的蒙戈测试 -collection并返回更新文档:

When I send {"name":"John Doe", "age":18, "country":"USA"} to my C# Web API with POST to api/test, I store it in my mongo test-collection and return the updated document:

[HttpPost]
[Route("{collection}")]
public IHttpActionResult Upsert(string collection, HttpRequestMessage request)
{
    var document = request.Content.ReadAsStringAsync().Result;
    var doc = BsonDocument.Parse(document);
    var result = new Db(collection).Upsert(doc).Result;
    return Ok(result);
}



.

public async Task<BsonDocument> Upsert(BsonDocument document)
{
    if (document.Contains("_id"))
    {
        await _collection.ReplaceOneAsync(w => w["_id"] == document["_id"], document);
    }
    else
    {
        await _collection.InsertOneAsync(document);
    }
    return document;
}

这工作,但现在的结果是一个key-value对象:

This works, but the result is now a key-value object:

[
  {
    "_name": "_id",
    "_value": "56e9364d942e1f287805e170"
  },
  {
    "_name": "name",
    "_value": "John Doe"
  },
  {
    "_name": "age",
    "_value": 18
  },
  {
    "_name": "country",
    "_value": "USA"
  }
]

我会想到的是:

{
    "_id": "56e9364d942e1f287805e170", 
    "name":"John Doe", 
    "age":18, 
    "country":"USA"
}

我怎样才能做到这一点?

How can I achieve this?

推荐答案

您可以直接返回 BsonDocument 这是的WebAPI序列化到JSON作为最好的,因为它可以,但不正确的。

You are returning directly a BsonDocument which WebAPI is serializing to JSON as best as it can, but not correctly.

尝试调用 MongoDB.Bson.BsonExtensionMethods.ToJson 将正确的序列化到JSON

Try calling MongoDB.Bson.BsonExtensionMethods.ToJson which will serialize it correctly to JSON ?

和返回的原始JSON:

And to return the raw JSON:

return new HttpResponseMessage { Content = new StringContent(document.ToJson(), System.Text.Encoding.UTF8, "application/json") };

这篇关于网页API返回扩展键 - 值对象,而不是原来的JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆