How do I parse a multidimensional JSON array using ServiceStack.Text?

1.6k views Asked by At

I read this post, but now I'm having trouble using it for my situation.

Given the following Google Maps JSON string (I am using the data structure used in Blitzmap.js):

{
   "zoom":12,
   "overlays":[
      {
         "type": "polygon",
         "paths":[
            [
               { "lat":52.06630340325415, "lng":5.749811642494365 },
               { "lat":52.066277072534014, "lng":5.758523457374736 },
               { "lat":52.06306460782621, "lng":5.758544915046855 },
               { "lat":52.063011942539184, "lng":5.749811642494365 }
            ]
         ]
      }
   ],
   "center":{ "lat":52.06465767289667, "lng":5.75417827877061 }
}

When using Newtonsoft.JSON I could do:

dynamic mapObjectsAsDynamic = (JObject)formPostedData.MapObjects;
foreach (var overlay in mapObjectsAsDynamic.overlays)
{
    if (overlay.type == "polygon")
    {
        foreach (var pathpart in overlay.paths)
        {
            foreach (var pathItem in pathpart.Children())
            {
                ... = pathItem.lat;
                ... = pathItem.lng;
            }
        }
    }
}

Now I like to use ServiceStack's JSON parser (ServiceStack.Text), but I am stuck on the paths.

I tried:

var mapObjectsAsJsonObject = JsonObject.Parse(request.MapObjects);
var trial1 = mapObjectsAsJsonObject.ArrayObjects("overlays");
var trial2 = trial1[0].ArrayObjects("paths");

Is there a similar Newtonsoft way?

1

There are 1 answers

2
Scott On BEST ANSWER

You can use the .JsonTo<T> extension method to convert your paths key to a Point[][] then you can easily traverse the collection.

Simple Point class:

public class Point
{
    public float lat { get; set; }
    public float lng { get; set; }
}

Usage (kept as similar to your usage in JSON.NET)

var mapObjects = JsonObject.Parse(request.MapObjects);

foreach(var overlay in mapObjects.ArrayObjects("overlays"))
{
    if(overlay.Get("type")=="polygon")
    {
        foreach(var pathPart in overlay.JsonTo<Point[][]>("paths"))
        {
            foreach(var pathItem in pathPart)
            {
                Console.WriteLine(pathItem.lat);
                Console.WriteLine(pathItem.lng);
            }
        }
    }
}

I hope this helps.