Parsing JSON with C-Sharp
The following
C# example tries to demonstrate how
JSON can be parsed by using the methods
DeserializeObject()
and
Deserialize()
.
With DeserializeObject
, the JSON document is parsed into a dynamic
variable. The document's individual values need then to be looked up with parsed["field_name"]
or parsed[array_pos]
.
When using Deserialize
, a class is required onto which the JSON document's name/value pairs can be mapped. IMHO, this makes it a bit neater to then access the values because the data-type is found in the class and they can be accessed with parsed.field_name
or parsed[array_pos]
.
using System;
using System.Web.Script.Serialization;
class C {
#pragma warning disable CS0649 // Field '…' is never assigned to, and will always have its default value …
internal class JSONData {
public Int32 num ;
public String txt ;
public String[] ary;
}
#pragma warning restore CS0649
static void Main() {
String JSONText = @"
{
""num"" : 42,
""txt"" : ""Hello, World"",
""ary"" :[
""zero"",
""one"" ,
""two""
]
}";
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
//
// Using DeserializeObject
//
dynamic result = jsonSerializer.DeserializeObject( JSONText );
// Console.WriteLine(result.GetType().FullName);
Console.WriteLine(result["num"]);
Console.WriteLine(result["txt"]);
Console.WriteLine(result["ary"][2]);
Console.WriteLine("");
//
// Using Serialize
//
JSONData data = (JSONData) jsonSerializer.Deserialize( JSONText, typeof(JSONData) );
Console.WriteLine(data.num);
Console.WriteLine(data.txt);
Console.WriteLine(data.ary[2]);
}
}
Parson JSON with PowerShell
In order to use
JavaScriptSerializer
in
PowerShell, the
assembly System.Web.Extension
must be loaded first:
$null = [System.Reflection.Assembly]::LoadWithPartialName('System.Web.Extensions')
With this assembly, a
JavaScriptSerializer
object can then be instantiated:
$jsonSerializer = new-object System.Web.Script.Serialization.JavaScriptSerializer
$json = $jsonSerializer.DeserializeObject('
{
"num": 42,
"txt": "Hello World",
"ary": ["zero", "one", "two", "three"],
"dct": {"elem_1": "foo", "elem_2": "bar", "elem_3": "baz"}
}')
write-host $json.num
write-host $json.txt
write-host $json.ary[1]
write-host $json.dct.elem_2
write-host $json.length
write-host $json.ary.length
write-host $json.dct.keys