1

I've one part of my JSON that looks like this:

enter image description here

Like you can see, in the JSON, the temperature "dictionary", is in fact a list of list of 2 element.

The first element is a timestamp, the second the temperature. Not sure why the provider of the service did it like this, but I don't really have the choice, I must do with it.

But in my C# object, I would like to have this as a dictionary, with timestamp as the key, and temperature as the value.

Is this possible?

//note, I've a custom converter that converts from long to DateTime     
public Dictionary<DateTime, double> Temperature { get; set; }

and deserializing like this:

JsonConvert.DeserializeObject<List<WeatherPredictionDay>>(content, new EpochConverter());

1 Answer 1

1

Yes, this can be done with a custom JsonConverter like this:

class TemperatureArrayConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return (objectType == typeof(Dictionary<DateTime, double>));
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        JArray ja = JArray.Load(reader);
        var dict = new Dictionary<DateTime, double>();
        foreach (JArray item in ja)
        {
            var key = item[0].ToObject<DateTime>(serializer);
            var val = item[1].ToObject<double>(serializer);
            dict.Add(key, val);
        }
        return dict;
    }

    public override bool CanWrite
    {
        get { return false; }
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

To use it, just mark your Temperature property with a [JsonConverter] attribute like this:

[JsonConverter(typeof(TemperatureArrayConverter))]
public Dictionary<DateTime, double> Temperature { get; set; }

Note: the above converter as written is intended to work with your existing EpochConverter to convert the timestamp values into DateTimes for the dictionary keys.

Here is a working demo: https://dotnetfiddle.net/TdxYjj

Sign up to request clarification or add additional context in comments.

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.