0

I have trouble to convert an c# object so an json array.

    public class ChartValue
    {        
        public DateTime Timestamp { get; set; }
        public float Value { get; set; }
    }

This object should be serialized like this for example:

[
   "2020-03-03T13:27:45",
    52.2
]

I need to stick to this json structure so adjusting is not possible. For serializian the Newtonsoft.json class is used.

Using a string array failed for me because the value is then "52.2" which is not accepted. Any ideas how to adjust the serialization or to create a "multitype" array

thanks for help!

rick
  • 79
  • 6
  • 2
    Have you tried `JsonConvert.SerializeObject(new object[] { chartValue.Timestamp, chartValue.Value });`? – Johnathan Barclay May 20 '20 at 15:22
  • You can do this with a custom `JsonConverter` for `ChartValue`. For a manual solution see [JSON deserialization - Map array indices to properties with JSON.NET](https://stackoverflow.com/a/36760064/3744182). For an automatic solution using reflection see [How to deserialize objects containing arrays of values with a fixed schema to strongly typed data classes?](https://stackoverflow.com/a/39462464/3744182). – dbc May 20 '20 at 15:25
  • https://stackoverflow.com/q/51637335/366064 – Bizhan May 20 '20 at 15:25

1 Answers1

1

I'm not sure that there is a build in way, but you can write your own JsonConverter using some reflection magic:

public class ChartValueToArrayJsonConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(ChartValue);
    }

    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)
    {
        if (value == null) return;

        writer.WriteStartArray();

        var properties = value.GetType().GetProperties();
        foreach (var property in properties)
            writer.WriteValue(value.GetType().GetProperty(property.Name).GetValue(value));

        writer.WriteEndArray();
    }
}

Usage:

JsonConvert.SerializeObject(new ChartValue(), new ChartValueToArrayJsonConverter()) // results in ["0001-01-01T00:00:00",0.0]

or mark your ChartValue class with [JsonConverterAttribute(typeof(ChartValueToArrayJsonConverter))] attribute if you want this behavior globally.

Guru Stron
  • 102,774
  • 10
  • 95
  • 132