-1

I have method where I call another API. From

var activeCustomers = await response.Content.ReadAsStringAsync(); I get string which contains [timestamp, value] objects:

{"values":[[1298937600000,1],[1459468800000,16],[1462060800000,527],[1464739200000,173],[1467331200000,132],[1470009600000,166],[1472688000000,151],[1475280000000,172],[1477958400000,139],[1480550400000,129],[1483228800000,116],[1485907200000,133],[1488326400000,180],[1491004800000,227],[1493596800000,281],[1496275200000,263],[1498867200000,230],[1501545600000,326],[1504224000000,403],[1506816000000,442],[1509494400000,1019],[1512086400000,650],[1514764800000,708],[1564617600000,2614],[1567296000000,2527],[1569888000000,3144],[1572566400000,3075],[1575158400000,2541],[1577836800000,2246],[1580515200000,2456],[1583020800000,885]]}

I want to parse these values into key value pairs, but I am not sure what's the most optimal way for that.

I tried removing beginning and ending of string and cast it as object but it stays as one big string inside the ienumerable:

            int index = activeCustomers.IndexOf(":");
            if (index > 0)
                activeCustomers = activeCustomers.Substring(index + 1);
            activeCustomers = activeCustomers.Remove(activeCustomers.Length - 1);

            var results = ((IEnumerable) activeCustomers).Cast<object>();

I also tried making regex for that but I am not very comfortable with that.

Pavel Anikhouski
  • 21,776
  • 12
  • 51
  • 66
user122222
  • 2,179
  • 4
  • 35
  • 78

1 Answers1

1

This just a JSON with array of arrays, which can be easily deserialized using Json.NET

var result = JsonConvert.DeserializeObject<Root>(activeCustomers);

or System.Text.Json

var result = JsonSerializer.Deserialize<Root>(activeCustomers);

Where Root is

public class Root
{
    public long[][] values { get; set; }
}

Then you can map the values property to any desired structure using Select method

var pairs = result.values.Select(v => new { timestamp = v[0], value = v[1] }).ToList();
Pavel Anikhouski
  • 21,776
  • 12
  • 51
  • 66