I am trying to get data from a Mixpanel API. The JSON result looks like this:
{"computed_at": "2019-11-19T10:36:33.908802+00:00", "legend_size": 1, "data": {"series": ["2019-11-11", "2019-11-12", "2019-11-13"], "values": {"page views": {"2019-11-12": 111, "2019-11-11": 573, "2019-11-13": 209}}}}
I want to populate this object with the values:
public class ResultData
{
public string Title { get; set; }
public int Value { get; set; }
public string Category { get; set; }
}
Specifically I want ResultData.Value
to be the sum of 111
, 573
and 209
(the page views over 3 days). Can anyone please help me to work out how to do this?
This is what I have tried so far:
public async Task<ResultData> GetData()
{
using (var client = new HttpClient())
{
try
{
var formattedDateFrom = DateTime.Today.AddDays(-1).ToString("yyyy-MM-dd");
var formattedDateTo = DateTime.Now.ToString("yyyy-MM-dd");
string baseUrl = "https://mixpanel.com/api/2.0/segmentation?from_date=" + formattedDateFrom + "&to_date=" + formattedDateTo + "&event=patient+-+booking+-+booked+appointment";
var response = await client.GetAsync(baseUrl);
var stringResult = await response.Content.ReadAsStringAsync();
var rawData = JsonConvert.DeserializeObject<ResultData>(stringResult);
var mixpanelResult = new ResultData();
mixpanelResult.Value = rawData.Value;
mixpanelResult.Title = "Page Views";
return await Task.FromResult(mixpanelResult);
} catch (HttpRequestException httpRequestException)
{
// Not sure what to put here but will try and work it out later
}
}
}
I know rawData.Value
isn't correct as it needs to be the sum of the page views, but at the moment it's not even deserializing. When I add a break point, rawData
is nothing more than the baseUrl
I'm a bit new at all this and any help would be really appreciated.
Well in your case your json
keys are dyanamic, so we can not deserialize
it based on any class because it will not going to match your json string.
I have tried something with the use of your json
, where you can get sum of your required keys. may be it is not best solution, but it may help you.
var obj = JObject.Parse("{\"computed_at\": \"2019-11-19T10:36:33.908802+00:00\", \"legend_size\": 1, \"data\": {\"series\": [\"2019-11-11\", \"2019-11-12\", \"2019-11-13\"], \"values\": {\"page views\": {\"2019-11-12\": 111, \"2019-11-11\": 573, \"2019-11-13\": 209}}}}");
var options = obj["data"]["values"]["page views"].ToList();
var sum = 0;
foreach (var item in options)
{
sum += Convert.ToInt32(item.FirstOrDefault());
}