Automatically bind pascal case c# model from snake case JSON in WebApi

前端 未结 3 994
一向
一向 2021-01-11 12:53

I am trying to bind my PascalCased c# model from snake_cased JSON in WebApi v2 (full framework, not dot net core).

Here\'s my api:

public class MyAp         


        
3条回答
  •  南笙
    南笙 (楼主)
    2021-01-11 13:23

    You can add cusrom json converter code like below. This should allow you to specify property mapping.

    public class ApiErrorConverter : JsonConverter
    {
    private readonly Dictionary     _propertyMappings = new Dictionary
    {
        {"name", "error"},
        {"code", "errorCode"},
        {"description", "message"}
    };
    
    public override bool CanWrite => false;
    
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
    
    public override bool CanConvert(Type objectType)
    {
        return objectType.GetTypeInfo().IsClass;
    }
    
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        object instance = Activator.CreateInstance(objectType);
        var props = objectType.GetTypeInfo().DeclaredProperties.ToList();
    
        JObject jo = JObject.Load(reader);
        foreach (JProperty jp in jo.Properties())
        {
            if (!_propertyMappings.TryGetValue(jp.Name, out var name))
                name = jp.Name;
    
            PropertyInfo prop = props.FirstOrDefault(pi =>
                pi.CanWrite && pi.GetCustomAttribute().PropertyName == name);
    
            prop?.SetValue(instance, jp.Value.ToObject(prop.PropertyType, serializer));
        }
    
        return instance;
        }
    }
    

    Then specify this attribute on your class.

    This should work.

    This blog explains the approach using console Application. https://www.jerriepelser.com/blog/deserialize-different-json-object-same-class/

提交回复
热议问题