Sign In Start Free Trial
Account

Add to playlist

Create a Playlist

Modal Close icon
You need to login to use this feature.
  • Book Overview & Buying The JavaScript JSON Cookbook
  • Table Of Contents Toc
  • Feedback & Rating feedback
The JavaScript JSON Cookbook

The JavaScript JSON Cookbook

By : Ray Rischpater
1 (2)
close
close
The JavaScript JSON Cookbook

The JavaScript JSON Cookbook

1 (2)
By: Ray Rischpater

Overview of this book

If you're writing applications that move structured data from one place to another, this book is for you. This is especially true if you've been using XML to do the job because it's entirely possible that you could do much of the same work with less code and less data overhead in JSON. While the book's chapters make some distinction between the client and server sides of an application, it doesn't matter if you're a frontend, backend, or full-stack developer. The principles behind using JSON apply to both the client and the server, and in fact, developers who understand both sides of the equation generally craft the best applications.
Table of Contents (17 chapters)
close
close
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.

notes
bookmark Notes and Bookmarks search Search in title playlist Add to playlist font-size Font size

Change the font size

margin-width Margin width

Change margin width

day-mode Day/Sepia/Night Modes

Change background colour

Close icon Search
Country selected

Close icon Your notes and bookmarks

Confirmation

Modal Close icon
claim successful

Buy this book with your credits?

Modal Close icon
Are you sure you want to buy this book with one of your credits?
Close
YES, BUY

Submit Your Feedback

Modal Close icon

Create a Note

Modal Close icon
You need to login to use this feature.

Delete Bookmark

Modal Close icon
Are you sure you want to delete it?
Cancel
Yes, Delete

Delete Note

Modal Close icon
Are you sure you want to delete it?
Cancel
Yes, Delete

Edit Note

Modal Close icon
Write a note (max 255 characters)
Cancel
Update Note