Tuesday, August 06, 2013

Windows Phone Tip: JSON to Data Contract Generator

If you are consuming a JSON web service, you can use the DataContractJsonSerializer class to deserialize a JSON string into an object so that you can manipulate the JSON string like an ordinary object. However, it is always a challenge to convert a JSON string into its class representation.

A good and easy way to convert a JSON string into its class representation is to use the tool at http://jsontodatacontract.azurewebsites.net/.

Suppose you have the following JSON string to convert:

{
    "postalcodes": [
        {
            "adminCode3":"70828",
            "adminName2":"Reutte",
            "adminName3":"Reutte",
            "adminCode2":"708",
            "postalcode":"6600",
            "adminCode1":"T",
            "countryCode":"AT",
            "lng":10.724044444,
            "placeName":"Ammerwald",
            "lat":47.490988888,
            "adminName1":"Tirol"
        },
        {
            "adminCode3":"70805",
            "adminName2":"Reutte",
            "adminName3":"Breitenwang",
            "adminCode2":"708",
            "postalcode":"6600",
            "adminCode1":"T",
            "countryCode":"AT",
            "lng":10.7050916669573,
            "placeName":"Bad Kreckelmoos",
            "lat":47.4900855904715,
            "adminName1":"Tirol"
        }
    ]
}

All you need to do is to navigate to http://jsontodatacontract.azurewebsites.net/ and paste it your JSON string. Also, give a name to the root class that will be generated for you (in this case I have called it PostalResult, select the language you want it to generate in (C#), and select the DataContract serialization model. Click the Generate code! button.



The following classes are automatically generated:

// Type created for JSON at <>
[System.Runtime.Serialization.DataContractAttribute()]
public partial class PostalResult
{   
    [System.Runtime.Serialization.DataMemberAttribute()]
    public Postalcodes[] postalcodes;
}

// Type created for JSON at <> --> postalcodes
[System.Runtime.Serialization.DataContractAttribute(Name="postalcodes")]
public partial class Postalcodes
{   
    [System.Runtime.Serialization.DataMemberAttribute()]
    public string adminCode3;
   
    [System.Runtime.Serialization.DataMemberAttribute()]
    public string adminName2;
   
    [System.Runtime.Serialization.DataMemberAttribute()]
    public string adminName3;
   
    [System.Runtime.Serialization.DataMemberAttribute()]
    public string adminCode2;
   
    [System.Runtime.Serialization.DataMemberAttribute()]
    public string postalcode;
   
    [System.Runtime.Serialization.DataMemberAttribute()]
    public string adminCode1;
   
    [System.Runtime.Serialization.DataMemberAttribute()]
    public string countryCode;
   
    [System.Runtime.Serialization.DataMemberAttribute()]
    public double lng;
   
    [System.Runtime.Serialization.DataMemberAttribute()]
    public string placeName;
   
    [System.Runtime.Serialization.DataMemberAttribute()]
    public double lat;
   
    [System.Runtime.Serialization.DataMemberAttribute()]
    public string adminName1;
}

You can paste the above classes into your project. To make use of it, use the following code snippet:

using System.Runtime.Serialization.Json;
using System.Diagnostics;
using System.IO;
using System.Text;

        private void JSON_Demo()
        {
            string json = @"
                {
                    ""postalcodes"": [
                    {
                        ""adminCode3"":""70828"",
                        ""adminName2"":""Reutte"",
                        ""adminName3"":""Reutte"",
                        ""adminCode2"":""708"",
                        ""postalcode"":""6600"",
                        ""adminCode1"":""T"",
                        ""countryCode"":""AT"",
                        ""lng"":10.724044444,
                        ""placeName"":""Ammerwald"",
                        ""lat"":47.490988888,
                        ""adminName1"":""Tirol""
                    },
                    {
                        ""adminCode3"":""70805"",
                        ""adminName2"":""Reutte"",
                        ""adminName3"":""Breitenwang"",
                        ""adminCode2"":""708"",
                        ""postalcode"":""6600"",
                        ""adminCode1"":""T"",
                        ""countryCode"":""AT"",
                        ""lng"":10.7050916669573,
                        ""placeName"":""Bad Kreckelmoos"",
                        ""lat"":47.4900855904715,
                        ""adminName1"":""Tirol""
                    }]
                }";

            //---convert the json string into a memorystream
            // object---
            MemoryStream stream = new
                MemoryStream(Encoding.UTF8.GetBytes(json));

            var serializer = new DataContractJsonSerializer(
                typeof(PostalResult));

            PostalResult result = (PostalResult)
                serializer.ReadObject(stream);

            for (int i = 0;
                 i <= result.postalcodes.Length - 1;
                 i++)
            {
                //---print out the place name---
                Debug.WriteLine(
                  result.postalcodes[i].placeName.ToString());

                //---print out the latitude---
                Debug.WriteLine(
                  result.postalcodes[i].lat.ToString());

                //---print out the longitude---
                Debug.WriteLine(
                  result.postalcodes[i].lng.ToString());
                Debug.WriteLine("----------");
            }
        }

The above code will print out the following result:

Ammerwald
47.490988888
10.724044444
----------
Bad Kreckelmoos
47.4900855904715
10.7050916669573
----------


No comments: