c# - 返回非结构化 BsonDocument 作为 ApiController 中的类属性

标签 c# mongodb asp.net-web-api json.net mongodb-.net-driver

与此类似question ,我有一个具有多种不同属性类型的类,包括 BsonDocument。

public class Report
{
    [BsonId, JsonIgnore]
    public ObjectId _id { get; set; }

    public string name { get; set; }

    [JsonIgnore]
    public BsonDocument layout { get; set; }

    [BsonIgnore, JsonProperty(PropertyName = "layout")]
    public string layout2Json
    {
        get { return layout.ToJson(); }
    }
}

其中存在 BsonDocument 的原因是布局属性是非结构化的,并且我不能有任何强类型的子类。现在,当 ApiController 返回此类时,我得到如下内容:

{
    name: "...",
    layout: "{type: "...", sth: "..."}"
}

但是我需要的是布局属性作为对象,而不是字符串。

JSON.NET 中是否有一种方法可以将 json 字符串(已经是有效的 json)作为对象而不是字符串插入?

以下方法有效,但似乎相当浪费:

[BsonIgnore, JsonProperty(PropertyName = "layout")]
public JObject layout2Json
{
    get { return JObject.Parse(layout.ToJson()); }
}

最佳答案

我也有类似的问题。我通过实现一个自定义 JsonConverter 解决了这个问题,它除了将原始值(已经是 Json)写入 Json writer 之外什么也不做:

public class CustomConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return true;
    }

    public override object ReadJson(Newtonsoft.Json.JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }

    public override void WriteJson(Newtonsoft.Json.JsonWriter writer, object value, JsonSerializer serializer)
    {
        writer.WriteRaw((string)value);
    }
}

然后,您使用该自定义转换器来装饰返回 BsonDocument 对象的字符串表示形式的属性:

public class Report
{
    [BsonId, JsonIgnore]
    public ObjectId _id { get; set; }

    public string name { get; set; }

    [JsonIgnore]
    public BsonDocument layout { get; set; }

    [BsonIgnore, JsonProperty(PropertyName = "layout")]
    [JsonConverter(typeof(CustomConverter))]
    public string layout2Json
    {
        get { return layout.ToJson(); }
    }
}

这样,您就可以摆脱双引号问题,并且非结构化对象将作为有效的 Json 对象而不是字符串返回。希望这有帮助。

关于c# - 返回非结构化 BsonDocument 作为 ApiController 中的类属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12883530/

相关文章:

c# - 在 android 下拉菜单中显示类似 र 的内容

c# - asp.hyperlink in gridview Format 0 as null

ruby-on-rails - 如何在json响应中将mongo id作为字符串返回

entity-framework-4 - 首先在 Entity Framework 代码中使用导航属性

c# - HttpClient 获取同一网站内的数据

c# - 使用更改使用变量的语句

c# - 模拟按键 C# .Net

node.js - 在 Windows Azure 上使用 MongoDB 运行 Node.js 时出现问题

node.js - mongoose 和 bcrypt-nodejs 不散列和保存密码

javascript - XMLHttpRequest 无法加载 No 'Access-Control-Allow-Origin' > 请求的资源上存在 header