JsonProperty - Use different name for deserialization, but use original name for serialization?

后端 未结 2 614
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-10 06:44

I am retrieving JSON from an API. I am using newtonsoft (this is json.net right?) to deserialize this into a list of objects. It works.

Unfortunately I also need to

2条回答
  •  心在旅途
    2020-12-10 07:18

    You can create a custom contract resolver that sets the property names back to the ones you've defined in the C# class before serilization. Below is some example code;

    class OriginalNameContractResolver : DefaultContractResolver
    {
        protected override IList CreateProperties(Type type, MemberSerialization memberSerialization)
        {
            // Let the base class create all the JsonProperties 
            IList list = base.CreateProperties(type, memberSerialization);
    
            // assign the C# property name
            foreach (JsonProperty prop in list)
            {
                prop.PropertyName = prop.UnderlyingName;
            }
    
            return list;
        }
    }
    

    Use it like this;

        JsonSerializerSettings settings = new JsonSerializerSettings();
        settings.Formatting = Formatting.Indented;
        if (useLongNames)
        {
            settings.ContractResolver = new OriginalNameContractResolver();
        }
    
        string response = JsonConvert.SerializeObject(obj, settings);
    

提交回复
热议问题