Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return unstructured BsonDocument as class-property in ApiController

Similar to this question, I have a class with several different property types, including 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(); }
    }
}

The reason for having BsonDocument in there, is that the layout-property is unstructured and I cannot have any strongly typed sub-classes. Now when the ApiController returns this class, I get something like this:

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

But what I need is the layout-property as an object, not a string.

Is there a way in JSON.NET to plug in a json-string - which is already valid json - as an object and not a string?

The following works, but seems quite wasteful:

[BsonIgnore, JsonProperty(PropertyName = "layout")]
public JObject layout2Json
{
    get { return JObject.Parse(layout.ToJson()); }
}
like image 298
Benjamin E. Avatar asked Mar 06 '26 21:03

Benjamin E.


1 Answers

I had a similar issue. I solved it by implementing a custom JsonConverter that will do nothing but to write the raw values (which is already Json) to the 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);
    }
}

Then you use that custom converter to decorate the property that returns the string representation of your BsonDocument object:

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(); }
    }
}

That way, you get rid of the double quote issue, and the unstructured object is returned as a valid Json object, not as a string. Hope this help.

like image 130
user1478550 Avatar answered Mar 09 '26 10:03

user1478550



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!