Reputation: 1033
I'm receiving the following Json response:
{"time_series_data":"[[2013-07-23T09:45:00,0.991],[2013-07-23T10:00:00,1.047],[2013-07-23T10:15:00,0.069],[2013-07-23T10:30:00,1.001],[2013-07-23T10:45:00,0.947],[2013-07-23T11:00:00,0.278],[2013-07-23T11:15:00,0.48],[2013-07-23T11:30:00,0.709],[2013-07-23T11:45:00,1.315],[2013-07-23T12:00:00,0.89],[2013-07-23T12:15:00,0.31],[2013-07-23T12:30:00,0.121],[2013-07-23T12:45:00,0.593],[2013-07-23T13:00:00,0.513],[2013-07-23T13:15:00,0.222],[2013-07-23T13:30:00,1.759],[2013-07-23T13:45:00,1.715],[2013-07-23T14:00:00,1.439],[2013-07-23T14:15:00,0.448],[2013-07-23T14:30:00,0.105]]"}
How would I read these dates and doubles into a list?
I've tried using Json.net, but I can't quite determine what the value collection above is called. Using the following code, I can pull out the value between the [[ and ]] brackets, but I'm not sure how to proceed from here.
JsonTextReader jR = new JsonTextReader(new StringReader(WebApiURL));
string data = "";
while (jR.Read())
{
if (jR.Value != null && jR.Value != "time_series_data")
data = jR.Value.ToString();
}
I can work with Json.net or native c#. Suggestions?
Upvotes: 0
Views: 1790
Reputation: 129827
Although the JSON response you are getting is valid JSON as a whole, it isn't in a form that would allow you to extract the dates and decimals easily with a standard JSON library.
The first problem is that the "array" part is actually inside a string value. You might think that you could simply take the string value and try to re-parse it as JSON, but then you will hit another problem: the string value by itself is not valid JSON array, as @Blender noticed. In order for it to be valid, the date values would need to be quoted, since JSON does not have a native date representation.
So, one way or another, you will have to do some manual processing on the data to extract the values. Fortunately, this is not very difficult using regular expressions to split up the string. Here's the approach I would take:
First, define a simple class to hold your data items.
class DataItem
{
public DateTime Date { get; set; }
public double Number { get; set; }
}
Then, picking up where you left off, you can parse apart your data
string like this:
List<DataItem> timeSeriesData = new List<DataItem>();
string[] pairs = Regex.Split(data, @"\[\[|\],\[|\]\]");
foreach (string pair in pairs)
{
if (!string.IsNullOrEmpty(pair) && char.IsDigit(pair[0])) // sanity check
{
string[] parts = pair.Split(',');
DateTime date = DateTime.Parse(parts[0], CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind);
double number = double.Parse(parts[1]);
timeSeriesData.Add(new DataItem { Date = date, Number = number });
}
}
Now you can use the timeSeriesData
list as you see fit.
Upvotes: 1
Reputation: 13409
You can use http://json2csharp.com/ to get the structure of objects for VALID json and you can use Json.net library to parse them.
Upvotes: 1