I have an object:
[JsonConverter(typeof(MessageConverter))]
public class Message
{
[JsonProperty(Order = 1)]
public long Id { get; set; }
[JsonProperty(Order = 2)]
public string Msg { get; set; }
[JsonProperty(Order = 3)]
public int Timestamp { get; set; }
}
Which I would like to serialise into an array in JSON of the following form:
[long, string, int]
This class would be nested in a hierarchy, so automatic conversion would be preferred.
I am currently using the following code, but this seems to contain a significant amount of repetition.
I was wondering if there were an attribute/more compact solution that would allow JSON.NET to use the provided attributes to provide the same functionality without the converter.
public class MessageConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(Message);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var arr = serializer.Deserialize<JToken>(reader) as JArray;
if (arr == null || arr.Count != 3)
throw new JsonSerializationException("Expected array of length 3");
return new Message
{
Id = (long)arr[0],
Msg = (string)arr[1],
Timestamp = (int)arr[2]
};
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var msg = value as Message;
var obj = new object[] { msg.Id, msg.Msg, msg.Timestamp };
serializer.Serialize(writer, obj);
}
}