Book Image

JavaScript JSON Cookbook

By : Ray Rischpater, Brian Ritchie, Ray Rischpater
Book Image

JavaScript JSON Cookbook

By: Ray Rischpater, Brian Ritchie, Ray Rischpater

Overview of this book

Table of Contents (17 chapters)
JavaScript JSON Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Reading and writing JSON in C#


C# is a common client-side language for rich applications as well as for writing the client implementation of web services running on ASP.NET. The .NET library includes JSON serialization and deserialization in the System.Web.Extensions assembly.

Getting ready

This example uses the built-in JSON serializer and deserializer in the System.Web.Extensions assembly, one of the many .NET libraries that are available. If you've installed a recent version of Visual Studio (see https://www.visualstudio.com/en-us/downloads/visual-studio-2015-downloads-vs.aspx), it should be available. All you need to do to use this assembly is include it in the assemblies your application references in Visual Studio by right-clicking the References item in your project, choosing Add Reference, and scrolling down to System.Web.Extensions in the Framework Assemblies list.

How to do it...

Here's a simple application that deserializes some JSON, as a dictionary of attribute-object pairs:

using System;
using System.Collections.Generic;
using System.Web.Script.Serialization;

namespace JSONExample
{
    public class SimpleResult
    {
        public string result;
    }

    class Program
    {
        static void Main(string[] args)
        {
            JavaScriptSerializer serializer = 
            new System.Web.Script.Serialization.
            JavaScriptSerializer();

            string json = @"{ ""call"":""KF6GPE"",""type"":
""l"",""time"":""1399371514"",""lasttime"":""1418597513"",
""lat"": 37.17667,""lng\": -122.14650,""result"": ""ok"" }";

dynamic result = serializer.DeserializeObject(json);
            foreach (KeyValuePair<string, object> entry in result)
            {
                var key = entry.Key;
                var value = entry.Value as string;
Console.WriteLine(String.Format("{0} : {1}", 
key, value));
            }
            Console.WriteLine(serializer.Serialize(result));

            var anotherResult = new SimpleResult { result="ok" };
            Console.WriteLine(serializer.Serialize(
            anotherResult));
        }
    }
}

How it works...

The System.Web.Extensions assembly provides the JavaScriptSerializer class in the System.Web.Script.Serialization namespace. This code begins by defining a simple class, SimpleResult, which we'll encode as JSON in our example.

The Main method first defines a JavaScriptSerializer instance, and then string containing our JSON. Parsing the JSON is as easy as calling the JavaScriptSerializer instance's DeserializeObject method, which returns an object whose type is determined at run-time based on the JSON you pass.

Tip

You can also use DeserializeObject to parse JSON in a type-safe manner, and then the type of the returned object matches the type you pass to the method. I'll show you how to do this in Chapter 7, Using JSON in a Type-safe Manner.

DeserializeObject returns a Dictionary of key-value pairs; the keys are the attributes in the JSON, and the values are objects representing the values of those attributes. In our example, we simply walk the keys and values in the dictionary, printing each. Because we know the type of the value in the JSON, we can simply cast it to the appropriate type (string, in this case) using the C# as keyword; if it wasn't string, we'd receive the value null. You can use as or the type inference of C# to determine the type of unknown objects in your JSON, making it easy to parse JSON for which you lack strict semantics.

The JavaScriptSerializer class also includes a Serialize method; you can either pass it as a dictionary of attribute-value pairs, as we do with our deserialized result, or you can pass it as an instance of a C# class. If you pass it as a class, it'll attempt to serialize the class by introspecting the class fields and values.

There's more...

The JSON implementation that Microsoft provides is adequate for many purposes, but not necessarily the best for your application. Other developers have implemented better ones that typically use the same interface as the Microsoft implementation. One good choice is Newtonsoft's Json.NET, which you can get at http://json.codeplex.com/ or from NuGet in Visual Studio. It supports a wider variety of .NET platforms (including Windows Phone), LINQ queries, XPath-like queries against the JSON, and is faster than the Microsoft implementation. Using it is similar to using the Microsoft implementation: install the package from the Web or NuGet, add a reference of the assembly to your application, and then use the JsonSerializer class in the NewtonSoft.Json namespace. It defines the same SerializeObject and DeserializeObject methods that the Microsoft implementation does, making switching to this library easy. James Newton-King, the author of Json.NET, makes it available under the MIT license.

As with other languages, you can also carry primitive types through the deserialization and serialization process. For example, after evaluating the following code, the resulting dynamic variable piResult will contain a floating-point number, 3.14:

string piJson = "3.14";
dynamic piResult = serializer.DeserializeObject(piJson);

See also

As I previously hinted, you can do this in a type-safe manner; we'll discuss more of this in Chapter 7, Using JSON in a Type-safe Manner. You'll do this using the generic method DeserializeObject<>, passing a type variable of the type you want to deserialize into.