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()); }
}
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:
Then you use that custom converter to decorate the property that returns the string representation of your BsonDocument object:
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.