Parse Json string in C#
I'm using Json.net in my project and it works great. In you case, you can do this to parse your json:
EDIT: I changed the code so it supports reading your json file (array)
Code to parse:
void Main()
{
var json = System.IO.File.ReadAllText(@"d:\test.json");
var objects = JArray.Parse(json); // parse as array
foreach(JObject root in objects)
{
foreach(KeyValuePair<String, JToken> app in root)
{
var appName = app.Key;
var description = (String)app.Value["Description"];
var value = (String)app.Value["Value"];
Console.WriteLine(appName);
Console.WriteLine(description);
Console.WriteLine(value);
Console.WriteLine("\n");
}
}
}
Output:
AppName
Lorem ipsum dolor sit amet
1
AnotherAppName
consectetur adipisicing elit
String
ThirdAppName
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua
Text
Application
Ut enim ad minim veniam
100
LastAppName
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat
ZZZ
BTW, you can use LinqPad to test your code, easier than creating a solution or project in Visual Studio I think.
json:
[{"ew":"vehicles","hws":["car","van","bike","plane","bus"]},{"ew":"countries","hws":["America","India","France","Japan","South Africa"]}]
c# code: to take only a single value, for example the word "bike".
//res=[{"ew":"vehicles","hws":["car","van","bike","plane","bus"]},{"ew":"countries","hws":["America","India","France","Japan","South Africa"]}]
dynamic stuff1 = Newtonsoft.Json.JsonConvert.DeserializeObject(res);
string Text = stuff1[0].hws[2];
Console.WriteLine(Text);
output:
bike
you can try with System.Web.Script.Serialization.JavaScriptSerializer
:
var json = new JavaScriptSerializer();
var data = json.Deserialize<Dictionary<string, Dictionary<string, string>>[]>(jsonStr);
Instead of an arraylist or dictionary you can also use a dynamic. Most of the time I use EasyHttp for this, but sure there will by other projects that do the same. An example below:
var http = new HttpClient();
http.Request.Accept = HttpContentTypes.ApplicationJson;
var response = http.Get("url");
var body = response.DynamicBody;
Console.WriteLine("Name {0}", body.AppName.Description);
Console.WriteLine("Name {0}", body.AppName.Value);
On NuGet: EasyHttp