Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
189 views
in Technique[技术] by (71.8m points)

c# - Json.NET Custom ValueProvider to convert Objects into Guid

I'm trying to create a custom ValueProvider for Json.NET that will skip serializing all the objects, and will just return a property of type Guid representing their primary Key instead (as a reference).

Example:

jsonData: {
    myObject: {
        id: "23e23-2gg5-6y666556-y6yg33",
        property2: ""
    }
}

Should become:

jsonData: {
    myObjectId: "23e23-2gg5-6y666556-y6yg33"
}

This is the code I wrote so far. I'm very close to make it work, but in my CustomValueProvider I don't seem to be able to get the object values. How can I do that?

    private class CustomValueProvider : IValueProvider
    {
        private readonly MemberInfo _member;

        public CustomValueProvider(MemberInfo member)
        {
            _member = member;
        }
        public void SetValue(object target, object value)
        {
            throw new NotImplementedException();
        }

        public object GetValue(object target)
        {
            return // WHAT HERE??
        }
    }

    private class CustomResolver : CamelCasePropertyNamesContractResolver
    {
        protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
        {
            var jsonProperty = base.CreateProperty(member, memberSerialization);

            if (jsonProperty.PropertyType.IsClass && jsonProperty.PropertyType != typeof(string))
            {
                jsonProperty = new JsonProperty
                {
                    PropertyName = member.Name.ToFirstCharLower() + "Id",
                    Readable = true,
                    ShouldSerialize = value => true,
                    PropertyType = typeof(Guid),
                    ValueProvider = new CustomValueProvider(member)
                };
            }

            return jsonProperty;
        }
    }

    private static readonly JsonSerializerSettings JsonSettings = new JsonSerializerSettings
    {
        ContractResolver = new CustomResolver(),
        Formatting = Formatting.Indented
    };
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You want to promote the "Id" value from inside the nested object to the parent object. To do that, you're going to need to chain together two value providers:

  • An outer value provider to get the value of the member.
  • An inner value provider to get the value of the Id of the member.

The following does this:

class NestedValueProvider : IValueProvider
{
    readonly IValueProvider outerProvider;
    readonly IValueProvider innerProvider;

    public NestedValueProvider(IValueProvider outerProvider, IValueProvider innerProvider)
    {
        if (outerProvider == null || innerProvider == null)
            throw new ArgumentNullException();
        this.outerProvider = outerProvider;
        this.innerProvider = innerProvider;
    }
    public void SetValue(object target, object value)
    {
        throw new NotImplementedException();
    }

    public object GetValue(object target)
    {
        var innerTarget = outerProvider.GetValue(target);
        if (innerTarget == null)
            return null;
        return innerProvider.GetValue(innerTarget);
    }
}

class CustomResolver : CamelCasePropertyNamesContractResolver
{
    // Using an inner resolver prevents difficulties with recursion.
    readonly CamelCasePropertyNamesContractResolver innerResolver = new CamelCasePropertyNamesContractResolver();

    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
    {
        var jsonProperty = base.CreateProperty(member, memberSerialization);

        if (!jsonProperty.PropertyType.IsPrimitive && jsonProperty.PropertyType != typeof(string) && jsonProperty.Readable)
        {
            var innerContract = innerResolver.ResolveContract(jsonProperty.PropertyType);
            if (innerContract is JsonObjectContract)
            {
                var objectContract = (JsonObjectContract)innerContract;
                var idProperty = objectContract.Properties.GetClosestMatchProperty(ResolvePropertyName("Id"));
                if (idProperty != null && idProperty.Readable && (innerResolver.ResolveContract(idProperty.PropertyType) is JsonPrimitiveContract))
                {
                    jsonProperty = new JsonProperty
                    {
                        PropertyName = ResolvePropertyName(member.Name + "Id"),
                        Readable = true,
                        PropertyType = idProperty.PropertyType,
                        ValueProvider = new NestedValueProvider(jsonProperty.ValueProvider, idProperty.ValueProvider),
                    };
                }
            }
            // Possibly handle innerContract is JsonArrayContract?
            // Possibly handle innerContract is JsonDictionaryConract?
        }

        return jsonProperty;
    }
}

Note the use of an inner contract resolver. This prevents problems with recursive calls for recursive types.

You might also want to consider handling collections of objects with IDs, or dictionaries of objects with IDs. For instance in the following object, the List<MyObject> and Dictionary<string, MyObject> properties will expose contents of MyObject:

public class RootObject
{
    // Correctly not remapped
    public string StringValue { get; set; }

    // Correctly remaps to a GUID.
    public MyObject MyObject { get; set; }

    // Remap to a List<Guid> ?
    public List<MyObject> MyObjectList { get; set; }

    // Remap to a Dictionary<string, Guid> ?
    public Dictionary<string, MyObject> MyObjectDictionary { get; set; }
}

public class MyObject
{
    public Guid Id { get; set; }
    public string Property2 { get; set; }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...