当我将{"name":"John Doe", "age":18, "country":"USA"}
发送到我的 C# Web API 并POST
to 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"
}
我怎样才能做到这一点?
您直接返回一个 WebAPI 正在尽可能序列化为 JSON 的BsonDocument
,但不正确。
尝试调用MongoDB.Bson.BsonExtensionMethods.ToJson
,这会将其正确序列化为 JSON ?
并返回原始 JSON:
return new HttpResponseMessage { Content = new StringContent(document.ToJson(), System.Text.Encoding.UTF8, "application/json") };
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());
}
}