Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c# - dynamically change the json property name and serialize

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

here is my json for two different entities

For customer

{
  "userName": "66666",
  "password": "test1234",  
  "customersList": [
    {
      "address": "Test Stree2",
      "customerNumber": "US01-000281",
      "city": ""

    }
  ]
}

For contact

{
  "userName": "66666",
  "password": "test1234",  
  "contactList": [
    {
      "address": "Test stree1",
      "contactNumber": "US01-000281",
      "city": ""

    }
  ]
}

and the model that is holding this data is as follows

public class URequest<T>
    {

        [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
        public string userName { get; set; }

        [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
        public string password { get; set; }    

       [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
        public IList<T> requestList { get; set; }

    }

in above code requestList could contain list of contacts or customer but while sending i want to change the requestList json property name to respective entity name i.e. for customer it will be customerList and for contact it will be contactList after serializing.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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<T>
{

    [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
    public string userName { get; set; }

    [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
    public string password { get; set; }

    [JsonIgnore]
    public IList<T> requestList { get; set; }

}

public class URequestConverter<T> : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return (objectType == typeof(URequest<T>));
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var objectType = value.GetType().GetGenericArguments()[0];
        URequest<T> typedValue = (URequest<T>) 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<Customer> request = new URequest<Customer>();
        request.password = "test";
        request.userName = "user";
        request.requestList = new List<Customer>();

        request.requestList.Add(new Customer() { Name = "customer" });

        JsonSerializerSettings settings = new JsonSerializerSettings();
        settings.Formatting = Formatting.Indented;
        settings.Converters.Add(new URequestConverter<Customer>());

        Console.WriteLine(JsonConvert.SerializeObject(request, settings));
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...