a developer's notes – a semi-technical web development BLOG

November 10, 2013

Parsing JSON to Key Value Pairs with JSON.NET

Filed under: C#,JSON — Duy Nguyen @ 8:30 pm
Tags: , , , , , , , , ,

I had to parse JSON into key value pairs recently. The key would be the path of the JSON property. Consider the following JSON:

{
    "car": {
        "type": [{
            "sedan": {
                "make": "honda",
                "model": "civics"
            }
        },
        {
            "coupe": {
                "make": "ford",
                "model": "escort"
            }
        }]
    }
}

For my key/value pair would look this.

Key: car_type_0_sedan_make 
Value: honda

Here is a console application to illustrate what I had to do.

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JsonGetKeyValue
{
    class Program
    {
        public static Dictionary<string, string> jsonKeyValues = new Dictionary<string, string>();

        static void Main(string[] args)
        {

            //JsonDotNetPathProperty();

            string namePrefix = "_myJson";

            string jsonInput = @"
            {
                ""car"": {
                    ""type"": [{
                        ""sedan"": {
                            ""make"": ""honda"",
                            ""model"": ""civic""
                        }
                    },
                    {
                        ""coupe"": {
                            ""make"": ""ford"",
                            ""model"": ""escort""
                        }
                    }]
                }
            }";

            JObject jo = new JObject();

            // Parse json *OBJECT*
            jo = JObject.Parse(jsonInput);

            string paramName = namePrefix;
            jsonKeyValues.Add(paramName, jsonInput);

            ParseJsonProperties(jo, paramName);

            foreach (var item in jsonKeyValues)
            {
                Console.Write("Key: ");
                Console.WriteLine(item.Key);
                Console.Write("Value: ");
                Console.WriteLine(item.Value);
                Console.WriteLine("");
            }

#if DEBUG
            Console.WriteLine("Press any key to close...");
            Console.ReadLine();
#endif

        }

        public static void ParseJsonProperties(JObject jObject, string paramName)
        {
            IEnumerable<JProperty> jObject_Properties = jObject.Properties();

            // Build list of valid property and object types 
            JTokenType[] validPropertyValueTypes = { JTokenType.String, JTokenType.Integer, JTokenType.Float, JTokenType.Boolean, JTokenType.Null, JTokenType.Date, JTokenType.Bytes, JTokenType.Guid, JTokenType.Uri, JTokenType.TimeSpan };
            List<JTokenType> propertyTypes = new List<JTokenType>(validPropertyValueTypes);

            JTokenType[] validObjectTypes = { JTokenType.String, JTokenType.Array, JTokenType.Object };
            List<JTokenType> objectTypes = new List<JTokenType>(validObjectTypes);

            string currentParamName = paramName; //Need to track where we are.

            foreach (JProperty property in jObject_Properties)
            {
                paramName = currentParamName;

                try
                {
                    if (propertyTypes.Contains(property.Value.Type))
                    {
                        ParseJsonKeyValue(property, paramName + "_" + property.Name.ToString());
                    }
                    else if (objectTypes.Contains(property.Value.Type))
                    {
                        //Arrays ex. { names: ["first": "John", "last" : "doe"]}
                        if (property.Value.Type == JTokenType.Array && property.Value.HasValues)
                        {
                            ParseJsonArray(property, paramName);
                        }

                        //Objects ex. { name: "john"}
                        if (property.Value.Type == JTokenType.Object)
                        {
                            JObject jo = new JObject();
                            jo = JObject.Parse(property.Value.ToString());
                            paramName = paramName + "_" + property.Name.ToString();

                            jsonKeyValues.Add(paramName, property.Value.ToString());

                            if (jo.HasValues)
                            {
                                ParseJsonProperties(jo, paramName);
                            }
                            
                        }
                    }
                }
                catch (Exception ex)
                {
                    throw;
                }
            } // End of ForEach
         
            paramName = currentParamName;            

        }

        public static void ParseJsonKeyValue(JProperty item, string paramName)
        {
            jsonKeyValues.Add(paramName, item.Value.ToString());
        }

        public static void ParseJsonArray(JProperty item, string paramName)
        {
            JArray jArray = (JArray)item.Value;

            paramName = paramName + "_" + item.Name.ToString();
            jsonKeyValues.Add(paramName, item.Value.ToString());

            string currentParamName = paramName; //Need track where we are

            try
            {
                for (int i = 0; i < jArray.Count; i++)
                {
                    paramName = currentParamName;

                    paramName = paramName + "_" + i.ToString();
                    jsonKeyValues.Add(paramName, jArray.Values().ElementAt(i).ToString());

                    JObject jo = new JObject();
                    jo = JObject.Parse(jArray[i].ToString());
                    IEnumerable<JProperty> jArrayEnum = jo.Properties();

                    foreach (JProperty jaItem in jArrayEnum)
                    {
                        // Prior to JSON.NET VER 5.0, there was no Path property on JTokens. So we had to track the path on our own.
                        var paramNameWithJaItem = paramName + "_" + jaItem.Name.ToString();

                        var itemValue = jaItem.Value.ToString(Formatting.None);
                        if (itemValue.Length > 0)
                        {
                            switch (itemValue.Substring(0, 1))
                            {
                                case "[":
                                    //Recusion call to itself
                                    ParseJsonArray(jaItem, paramNameWithJaItem);
                                    break;
                                case "{":
                                    //Create a new JObject and parse
                                    JObject joObject = new JObject();
                                    joObject = JObject.Parse(itemValue);

                                    //For this value, reparse from the top
                                    ParseJsonProperties(joObject, paramNameWithJaItem);
                                    break;
                                default:
                                    ParseJsonKeyValue(jaItem, paramNameWithJaItem);
                                    break;
                            }
                        }
                    }
                } //end for loop

                paramName = currentParamName;
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        public static void JsonDotNetPathProperty()
        {
            string json = @"
            {
                ""car"": {
                    ""type"": [{
                        ""sedan"": {
                            ""make"": ""honda"",
                            ""model"": ""civic""
                        }
                    },
                    {
                        ""coupe"": {
                            ""make"": ""ford"",
                            ""model"": ""escort""
                        }
                    }]
                }
            }";

            JObject obj = JObject.Parse(json);
            JToken token = obj["car"]["type"][0]["sedan"]["make"];
            Console.WriteLine(token.Path + " -> " + token.ToString());
        }

    }
}

September 12, 2013

Parsing Google Maps API V3 JSON Response in C# .NET 4

Filed under: ASP.NET MVC,C# — Duy Nguyen @ 10:53 pm
Tags: , , , , , , , , , ,

Here is what you will need to parse responses from Google Maps V3.

Request to the following URL:
http://maps.googleapis.com/maps/api/geocode/json?address=1000+broad+street+road%2c+short+pump%2c+VA+23233&sensor=false

Reponse:

{
   'results' : [
	  {
		 'address_components' : [
			{
			   'long_name' : 'Broad Street Road',
			   'short_name' : 'Broad Street Rd',
			   'types' : [ 'route' ]
			},
			{
			   'long_name' : 'Virginia',
			   'short_name' : 'VA',
			   'types' : [ 'administrative_area_level_1', 'political' ]
			},
			{
			   'long_name' : 'United States',
			   'short_name' : 'US',
			   'types' : [ 'country', 'political' ]
			}
		 ],
		 'formatted_address' : 'Broad Street Road, VA, USA',
		 'geometry' : {
			'bounds' : {
			   'northeast' : {
				  'lat' : 37.6689969,
				  'lng' : -77.64866649999999
			   },
			   'southwest' : {
				  'lat' : 37.662306,
				  'lng' : -77.6778078
			   }
			},
			'location' : {
			   'lat' : 37.6657544,
			   'lng' : -77.66309579999999
			},
			'location_type' : 'GEOMETRIC_CENTER',
			'viewport' : {
			   'northeast' : {
				  'lat' : 37.6689969,
				  'lng' : -77.64866649999999
			   },
			   'southwest' : {
				  'lat' : 37.662306,
				  'lng' : -77.6778078
			   }
			}
		 },
		 'partial_match' : true,
		 'types' : [ 'route' ]
	  }
   ],
   'status' : 'OK'
}

These are the classes you need to define so you can deserialize the json into a type object.

public class GoogleGeoCodeResponse
{
	public results[] results { get; set; }
	public string status { get; set; }
}

public class results
{
	public address_component[] address_components { get; set; }
	public string formatted_address { get; set; }
	public geometry geometry { get; set; }
	public string partial_match { get; set; }
	public string[] types { get; set; }
}

public class geometry
{
	public bounds bounds { get; set; }
	public location location { get; set; }
	public string location_type { get; set; }
	public viewport viewport { get; set; }
}

public class bounds
{
	public northeast northeast { get; set; }
	public southwest southwest { get; set; }
}

public class viewport
{
	public northeast northeast { get; set; }
	public southwest southwest { get; set; }
}

public class northeast : location
{
}

public class southwest : location
{
}

public class location
{
	public decimal lat { get; set; }
	public decimal lng { get; set; }
}

public class address_component
{
	public string long_name { get; set; }
	public string short_name { get; set; }
	public string[] types { get; set; }
}

Here is the code you can use to decode your response.

private void GoogleJsonDecode()
{
	string response = @"
						{
						   'results' : [
							  {
								 'address_components' : [
									{
									   'long_name' : 'Broad Street Road',
									   'short_name' : 'Broad Street Rd',
									   'types' : [ 'route' ]
									},
									{
									   'long_name' : 'Virginia',
									   'short_name' : 'VA',
									   'types' : [ 'administrative_area_level_1', 'political' ]
									},
									{
									   'long_name' : 'United States',
									   'short_name' : 'US',
									   'types' : [ 'country', 'political' ]
									}
								 ],
								 'formatted_address' : 'Broad Street Road, VA, USA',
								 'geometry' : {
									'bounds' : {
									   'northeast' : {
										  'lat' : 37.6689969,
										  'lng' : -77.64866649999999
									   },
									   'southwest' : {
										  'lat' : 37.662306,
										  'lng' : -77.6778078
									   }
									},
									'location' : {
									   'lat' : 37.6657544,
									   'lng' : -77.66309579999999
									},
									'location_type' : 'GEOMETRIC_CENTER',
									'viewport' : {
									   'northeast' : {
										  'lat' : 37.6689969,
										  'lng' : -77.64866649999999
									   },
									   'southwest' : {
										  'lat' : 37.662306,
										  'lng' : -77.6778078
									   }
									}
								 },
								 'partial_match' : true,
								 'types' : [ 'route' ]
							  }
						   ],
						   'status' : 'OK'
						}";

	JavaScriptSerializer jss = new JavaScriptSerializer();
	GoogleGeoCodeResponse test = jss.Deserialize<GoogleGeoCodeResponse>(response);
}

Now you have this!

googleGeoCodeObj

April 11, 2013

Parsing a Query String into an array with JavaScript

Filed under: Javascript / JQuery — Duy Nguyen @ 9:50 pm
Tags: , , , , , , , , ,

This brilliant method belongs to Joe Zim’s JavaScript Blog.

Here is the function.

    var parseQueryString = function( queryString ) {
        var params = {}, queries, temp, i, l;
     
        // Split into key/value pairs
        queries = queryString.split("&");
     
        // Convert the array of strings into an object
        for ( i = 0, l = queries.length; i < l; i++ ) {
            temp = queries[i].split('=');
            params[temp[0]] = temp[1];
        }
     
        return params;
    };

Using the function.

   function Test() {
        var qstring = "apple=7sf&orange=242&bananna=47614&cherry=8139";
        var myNewArray = parseQueryString(qstring);
    }

As you can see, you now have an array of all of your query strings!

parseQstring

Create a free website or blog at WordPress.com.