1

i need to accept a json string that contains fields which are of type uint32[] (with length of 2) to a long.

class to be serialized to:

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

what i need:

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

ive seen this answer: https://stackoverflow.com/a/4093750/8099383 which looks like what i need but i need to include a custom function to convert from uint32[] to long (i think?), and it seems this works in relation to interfaces rather than native types.

in case it makes a difference, the long is made up of uint32[0] = lower & uint32[1] = higher.

Pavel_K
  • 10,748
  • 13
  • 73
  • 186
kodty
  • 159
  • 6

1 Answers1

1

You can tell json to deserialize height as original type (uint[]), but expose to user another property of long type. Something like (untested, but should give an idea):

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; }
}

Notice: _height is private and Height is marked to be ignored by json.

Sinatr
  • 20,892
  • 15
  • 90
  • 319