dynamically change the json property name and serialize

前端 未结 2 595
旧巷少年郎
旧巷少年郎 2020-12-12 06:50

i want to change the json property name dynamically and serialize the object.

here is my json for two different entities

For customer



        
2条回答
  •  隐瞒了意图╮
    2020-12-12 07:21

    You can create a custom JsonConverter.

    Using custom JsonConverter in order to alter the serialization of the portion of an object

    Example

    public class Customer
    {
        public string Name { get; set; }
    }
    
    public class Client
    {
        public string Name { get; set; }
    }
    
    public class URequest
    {
    
        [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
        public string userName { get; set; }
    
        [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
        public string password { get; set; }
    
        [JsonIgnore]
        public IList requestList { get; set; }
    
    }
    
    public class URequestConverter : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return (objectType == typeof(URequest));
        }
    
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var objectType = value.GetType().GetGenericArguments()[0];
            URequest typedValue = (URequest) value;
    
            JObject containerObj = JObject.FromObject(value);
    
            containerObj.Add($"{objectType.Name.ToLower()}List", JToken.FromObject(typedValue.requestList));
            containerObj.WriteTo(writer);
        }
    
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }
    }
    

    You can use it like this

        [TestMethod]
        public void TestMethod1()
        {
            URequest request = new URequest();
            request.password = "test";
            request.userName = "user";
            request.requestList = new List();
    
            request.requestList.Add(new Customer() { Name = "customer" });
    
            JsonSerializerSettings settings = new JsonSerializerSettings();
            settings.Formatting = Formatting.Indented;
            settings.Converters.Add(new URequestConverter());
    
            Console.WriteLine(JsonConvert.SerializeObject(request, settings));
        }
    

提交回复
热议问题