Search code examples
c#json.netmixpanel

Deserialize Mixpanel Data API Event JSON C#


I'm trying to deserialize some json from the mixpanel data api using Newtonsoft Json, I've created a class, but I get errors. The problem lies with the fact that property A and B in the 'values' object aren't fixed names. Hence why I thought using Dictionary<string, NameValueCollection> would work. Any help with this would be great

JSON:

{
  "legend_size": 1,
  "data": {
    "series": [
      "2014-06-30"
    ],
    "values": {
      "A": {
        "2014-06-30": 1082,
        "2014-06-23": 4249
      },
      "B": {
        "2014-06-30": 1082,
        "2014-06-23": 4249
      }
    }
  }
}

Results.cs

public class Result
{
    [JsonProperty("data")]
    public Data Data { get; set; }

    [JsonProperty("legend_size")]
    public int LegendSize { get; set; }
}

public class Data
{
    [JsonProperty("series")]
    public IEnumerable<DateTime> Series { get; set; }

    [JsonConverter(typeof(MixEventValuesConverter))]
    [JsonProperty("values")]
    public IDictionary<string, NameValueCollection> Values { get; set; }
}

I created a converter (for the first time ever, i don't really know what I'm doing with it!) and tried to return just an empty value for now, but I get the error 'Additional text found in JSON string after finishing deserializing object.'.

MixEventValuesConverter.cs

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

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var col = new NameValueCollection();
            col.Add("testtest", "vallll");

            var dic = new Dictionary<string, NameValueCollection>();
            dic.Add("testt", col);

            return dic;
        }

        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(MixEventResult);
        }
    }

Solution

  • You don't need a converter here; just use a nested Dictionary like this:

    public class Data
    {
        [JsonProperty("series")]
        public IEnumerable<DateTime> Series { get; set; }
    
        [JsonProperty("values")]
        public IDictionary<string, IDictionary<DateTime, int>> Values { get; set; }
    }