Serialization of Json.NET with additional properties; Saving Serializer Settings

I would like to introduce some metadata properties in json output for instances of a particular type when JSON.NET serializes the type.

What is the best way to introduce these additional properties while maintaining context and serialization settings?


I know that I can implement JsonConverterand add it to the serializer settings. Here's an example implementation WriteJson:

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
    var Json = JObject.FromObject(value, serializer);

    //modify Json by adding some properties ...

    Json.WriteTo(writer);
}

However, this presents several problems that I'm not sure how to get around:

If the serializer is configured by installation:

ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore

then the call attempt JObject.FromObject(value, serializer)does not serialize anything, since JSON.NET has already determined that the value is serialized (and therefore it ignores further attempts to serialize the same link).

ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, . JObject.FromObject(value, serializer) WriteJson JsonConverter.

JObject.FromObject(value) ( ), . , json, , .. , , , .

, json, ?


. , factory Func<JsonSerializerSettings> JsonConverter. , , . , , .

+4
1

, IContractResolver CreateProperties, IValueProvider, .

, JsonConverter , , .

protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
    var Result = base.CreateProperties(type, memberSerialization);

    //check if this is a type we add properties to
    if (IsAnnotatedType(type))
    {
        Result.Add(new JsonProperty
        {
            PropertyType = typeof(string),
            PropertyName = "AdditionalProperty",
            Readable = true,
            Writable = false,

            //value provider will receive the object instance when GetValue is called
            ValueProvider = new AdditionalPropertyValueProvider()
        });
    }

    return Result;
}
+5

All Articles