6

Using Newton.Json for Json Serializing. What JsonSerializerSettings to apply ,when I have to Json serialize an object with property as Byte array ,and then to display byte array in Hex format..

For eg

class A
{
  public int X {get;set;}
  public byte[] Y {get;set;}  
}

When I serialize A to json , I do not get value for Y as i have set ... Output for byte[] should be in hex

3
  • site james.newtonking.com/projects/json-net.aspx, docs james.newtonking.com/projects/json/help Commented Aug 6, 2012 at 13:52
  • serializing new A() { X = 1001, Y = new byte[] { 0, 1, 4, 8 } } gives me {"X":1001,"Y":"AAEECA=="}, is this what you are expecting? Commented Aug 6, 2012 at 13:55
  • yes this is output , but i require actual value to display as "00010408" in hex Commented Aug 6, 2012 at 14:08

3 Answers 3

8
var json = JsonConvert.SerializeObject(new MyTestClass());

public class MyTestClass
{
    public string s = "iiiii";

    [JsonConverter(typeof(ByteArrayConvertor))]
    public byte[] buf = new byte[] {1,2,3,4,5};
}

public class ByteArrayConvertor : Newtonsoft.Json.JsonConverter
{

    public override bool CanConvert(Type objectType)
    {
        return objectType==typeof(byte[]);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        byte[] arr = (byte[])value;
        writer.WriteRaw(BitConverter.ToString(arr).Replace("-", ""));
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

I had to change "WriteRaw" to "WriteValue" to get this to work.
4

Just overwrite converters in JsonSerializerSettings, better than attribute in properties

private class SerializationTest
{
    public byte[] Bytes => new byte[] { 11, 22, 33, 44, 0xAA, 0xBB, 0xCC };
}

private class ByteArrayHexConverter : JsonConverter
{
    public override bool CanConvert(Type objectType) => objectType == typeof(byte[]);

    public override bool CanRead => false;
    public override bool CanWrite => true;

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) => throw new NotImplementedException();

    private readonly string _separator;

    public ByteArrayHexConverter(string separator = ",") => _separator = separator;

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var hexString = string.Join(_separator, ((byte[])value).Select(p => p.ToString("X2")));
        writer.WriteValue(hexString);
    }
}

private static void Main(string[] args)
{
    var setting = new JsonSerializerSettings { Converters = { new ByteArrayHexConverter() } };
    var json = JsonConvert.SerializeObject(new SerializationTest(), setting);
    Console.WriteLine(json); // {"Bytes":"0B,16,21,2C,AA,BB,CC"}
}

Comments

0

Includes both serialization and deserialization

    public class A
    {
        public int X { get; set; }

        [JsonProperty(ItemConverterType = typeof(BytesToHexConverter))]
        public byte[] Y { get; set; }
    }

    public class BytesToHexConverter : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(byte[]);
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.String)
            {
                var hex = serializer.Deserialize<string>(reader);
                if (!string.IsNullOrEmpty(hex))
                {
                    return Enumerable.Range(0, hex.Length)
                         .Where(x => x % 2 == 0)
                         .Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
                         .ToArray();
                }
            }
            return Enumerable.Empty<byte>();
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var bytes = value as byte[];
            var @string = BitConverter.ToString(bytes).Replace("-", string.Empty);
            serializer.Serialize(writer, @string);
        }
    }

    public static void Main(string[] args)
    {
        var a = new A() { X = 1001, Y = new byte[] { 0, 1, 4, 8 } };
        var s = new JsonSerializer();

        var sb = new StringBuilder();
        var sw = new StringWriter(sb);

        s.Converters.Add(new BytesToHexConverter());
        s.Serialize(sw, a);
        var json = sb.ToString();

        var sr = new StringReader(json);
        var readback = s.Deserialize(sr, typeof(A));

        Console.WriteLine(sw);
        Console.WriteLine("End...");
        Console.ReadLine();
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.