简体   繁体   English

Newtonsoft Json 反序列化 1 json 属性为十进制或整数 c# 属性

[英]Newtonsoft Json Deserialization 1 json property to decimal or int c# properties

How to achieve below deserialization.下面如何实现反序列化。 value in JSON sometime int and sometime it's decimal . JSON 中的value有时是int有时是decimal I am working under multiple restrictions so -我在多重限制下工作,所以 -

  1. can't change value as int property.不能将value更改为int属性。 It may break existing contract and this is use all around system.它可能会破坏现有的合同,这是在整个系统中使用。
  2. have to use MyType as this is use all around system必须使用MyType因为这是在整个系统中使用

I noticed decimal in JSON to int deserialization will throw exception.我注意到 JSON 中的decimalint反序列化会引发异常。

public class MyType
{
    [JsonProperty("type")]
    [Required]
    public string Type { get; set; }

    [JsonProperty("value")] // existing field 
    public int Value { get; set; }

    [JsonProperty("value")] // new field planning to add for new data
    public decimal Value2 { get; set; }
}

You could leverage a custom JsonConverter .您可以利用自定义JsonConverter Decorate your class:装饰您的 class:

[JsonConverter(typeof(CustomConverter))]
public class MyType
{
    [JsonProperty("type")]
    [Required]
    public string Type { get; set; }

    [JsonProperty("value")] // existing field 
    public int Value { get; set; }

    // new field planning to add for new data
    public decimal Value2 { get; set; }
}

Where CustomConverter is defined (roughly):定义CustomConverter的地方(大致):

public class CustomConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        throw new NotImplementedException();
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        JObject jObject = JToken.Load(reader) as JObject;

        MyType myType = new MyType();
        myType.Type = jObject.GetValue("type").ToString();

        JToken tokenValue = jObject["value"];
        if (tokenValue.Type == JTokenType.Integer)
        {
            myType.Value = int.Parse(tokenValue.ToString());
        }
        else if (tokenValue.Type == JTokenType.Float) {
            myType.Value2 = decimal.Parse(tokenValue.ToString());
        }

        return myType;
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }

Note that one of Value and Value2 is implicitly set to 0 whereas the other property contains deserialized value.请注意, ValueValue2之一被隐式设置为 0,而另一个属性包含反序列化的值。

To test the solution execute:要测试解决方案,请执行:

string json = @"{type:""Type1"",value: 27.99}";
MyType temp = JsonConvert.DeserializeObject<MyType>(json);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM