【问题标题】:How to convert a property type when deserializing json?反序列化json时如何转换属性类型?
【发布时间】:2017-11-21 19:29:51
【问题描述】:

我需要接受一个 json 字符串,其中包含 uint32[] 类型(长度为 2)到 long 类型的字段。

要序列化的类:

public class ChainHeightDTO
{
    [JsonProperty("height")]
    public uint[] Height { get; set; }
}

我需要什么:

public class ChainHeightDTO
{
    [JsonProperty("height")]
    [JsonConverter(typeof(TypeConversionClass))]
    public long Height { get; set; }
}

我看到了这个答案:https://stackoverflow.com/a/4093750/8099383 这看起来像我需要的,但我需要包含一个自定义函数来从 uint32[] 转换为 long(我认为?),这似乎与接口有关而不是本机类型。

如果有所不同,long 由 uint32[0] = lower & uint32[1] = Higher组成。

【问题讨论】:

    标签: c# json


    【解决方案1】:

    您可以告诉 json 将 height 反序列化为原始类型 (uint[]),但向用户公开另一个 long 类型的属性。类似的东西(未经测试,但应该给出一个想法):

    public class ChainHeightDTO
    {
        [JsonProperty("height")]
        private uint[] _height 
        {
            get { return new uint[] { Height % 256, Height / 256 }; }
            set { Height = value[0] + value[1] * 256; }
        }
        [JsonIgnore]
        public long Height { get; set; }
    }
    

    注意:_heightprivateHeight 被 json 标记为忽略。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-19
      • 1970-01-01
      • 2016-11-29
      • 1970-01-01
      • 1970-01-01
      • 2017-11-15
      • 1970-01-01
      相关资源
      最近更新 更多