【问题标题】:Web Api returns expanded key-value object instead of original JSON objectWeb Api 返回扩展键值对象而不是原始 JSON 对象
【发布时间】:2016-03-16 10:40:22
【问题描述】:

当我使用POST{"name":"John Doe", "age":18, "country":"USA"} 发送到我的C# Web API 到api/test 时,我将它存储在我的mongo test-collection 中并返回更新后的文档:

[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;
}

这可行,但结果现在是一个键值对象:

[
  {
    "_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"
}

我怎样才能做到这一点?

【问题讨论】:

    标签: c# mongodb json.net asp.net-web-api2


    【解决方案1】:

    您将直接返回一个BsonDocument,WebAPI 正在尽可能地序列化为 JSON,但不正确。

    尝试调用MongoDB.Bson.BsonExtensionMethods.ToJson,它将正确序列化为 JSON ?

    并返回原始 JSON:

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

    【讨论】:

    • 我不认为这是一个真正的解决方案,因为您每次需要返回 bson 文档时都需要这样做,这是使其工作但不可维护的快速方法一个
    • @LouieAlmeda 它完美地回答了我的问题,如果您关心可维护性,请像我一样将其包装在自定义方法/类中。
    • @Sven 你介意分享你的解决方案吗?谢谢:)
    • 代码是概念证明,由您决定如何以可维护的方式集成它。最简单的是创建一个函数:gist.github.com/chris03/c34d865a5ae9db81e00a8ece368782c4
    【解决方案2】:

    MongoDB.Bson中有一个扩展方法“ToJson”,可以返回你喜欢的json。

    您可以在您的序列化设置中添加转换器,它将使用此方法:

    public class BsonDocumentJsonConverter : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(BsonDocument);
        }
    
        public override bool CanRead
        {
            get
            {
                return false;
            }
        }
    
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }
    
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            string json = (value as BsonDocument).ToJson();
            writer.WriteRawValue(json);
        }
    }
    

    在您的 WebApiConfig 中添加转换器:

    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            var jsonFormatter = config.Formatters.JsonFormatter;
            var settings = jsonFormatter.SerializerSettings;
    
            settings.Converters.Add(new BsonDocumentJsonConverter());
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-06-29
      • 2020-07-23
      • 1970-01-01
      • 2020-01-10
      • 1970-01-01
      • 2018-07-03
      • 2015-08-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多