Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse JSON without JSON.NET library?

Tags:

json

c#

windows-8

I'm trying to build a Metro application for Windows 8 on Visual Studio 2011. and while I'm trying to do that, I'm having some issues on how to parse JSON without JSON.NET library (It doesn't support the metro applications yet).

Anyway, I want to parse this:

{    "name":"Prince Charming",    "artist":"Metallica",    "genre":"Rock and Metal",    "album":"Reload",    "album_image":"http:\/\/up203.siz.co.il\/up2\/u2zzzw4mjayz.png",    "link":"http:\/\/f2h.co.il\/7779182246886" } 
like image 214
Eli Revah Avatar asked Mar 05 '12 19:03

Eli Revah


1 Answers

You can use the classes found in the System.Json Namespace which were added in .NET 4.5. You need to add a reference to the System.Runtime.Serialization assembly

The JsonValue.Parse() Method parses JSON text and returns a JsonValue:

JsonValue value = JsonValue.Parse(@"{ ""name"":""Prince Charming"", ..."); 

If you pass a string with a JSON object, you should be able to cast the value to a JsonObject:

using System.Json;   JsonObject result = value as JsonObject;  Console.WriteLine("Name .... {0}", (string)result["name"]); Console.WriteLine("Artist .. {0}", (string)result["artist"]); Console.WriteLine("Genre ... {0}", (string)result["genre"]); Console.WriteLine("Album ... {0}", (string)result["album"]); 

The classes are quite similar to those found in the System.Xml.Linq Namespace.

like image 135
dtb Avatar answered Sep 20 '22 15:09

dtb