Sunday, October 19, 2014

Parse JSON string using JSON.Net

First add Newtonsoft.Json to the references of the project. Now suppose we want to parse the following JSON string which contains an array of objects:

"[{"id":"1","userid":"1","name":"node:19:1","datatype":"1","tag":"Node:19","public":"0","size":"488","engine":"5","time":1413697602,"value":"215"},..., {"id":"20", ...}]"

The C# code as as follows:

dynamic data = JsonConvert.DeserializeObject(json_string);
for (int i = 0; i < data.Count; ++i)
dynamic item = data[i];

string id = (string);
string name = (string);
string tag = (string)item.tag;
int time = (int)item.time;
string value = (string)item.value;

double dbl_value = 0;
double.TryParse(value, out dbl_value);

//do something about the item here

No comments:

Post a Comment