Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Newton Soft Json JsonSerializerSettings for object with Property as byte array

Tags:

c#

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

like image 359
user334223 Avatar asked Aug 06 '12 13:08

user334223


People also ask

Are bytes JSON serializable?

Conclusion # The Python "TypeError: Object of type bytes is not JSON serializable" occurs when we try to convert a bytes object to a JSON string. To solve the error, call the decode() method on the bytes object to decode the bytes to a string before serializing to JSON.

How do you serialize an array in JSON?

To serialize a collection - a generic list, array, dictionary, or your own custom collection - simply call the serializer with the object you want to get JSON for. Json.NET will serialize the collection and all of the values it contains.

What does Jsonconvert Deserializeobject do?

Deserializes the JSON to the specified . NET type. Deserializes the JSON to the specified . NET type using a collection of JsonConverter.

Does JSON serialize private fields?

All fields, both public and private, are serialized and properties are ignored.


2 Answers

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("-", ""));
    }
}
like image 144
L.B Avatar answered Sep 27 '22 19:09

L.B


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"}
}
like image 37
IlPADlI Avatar answered Sep 27 '22 18:09

IlPADlI