Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating GeoJSON output from Well Known Text with C#

I am trying to create JSON output that resembles the GeoJSON format described here: http://geojson.org/geojson-spec.html

In particular, I have text being returned from my datasource in Text format and would like to convert my DTOs to JSON in the format shown n my comments below. The main issue I am having is trying to create the coordinates array [[ ... ]] without property names.

Code:

/*

                Geometry Text Format from database:  POLYGON ((319686.3666000003 7363726.7955, 319747.05190000031 7363778.9233, 319700.78849999979 7363832.7814, 319640.10329999961 7363780.6536, 319686.3666000003 7363726.7955))

                And we want format:
                "geometry": {
                    "type": "Polygon",
                    "coordinates": [[
                        [319686.3666000003, 7363726.795],
                        [319747.0519000003, 7363778.9233],
                        [319700.78849999979, 7363832.7814],
                        [319640.10329999961, 7363780.6536],
                        [319686.3666000003, 7363726.795]
                    ]]
                }

                */


                // Strip out everything except the coordinates
                var coordRawText = myWkt.Replace("POLYGON ((", "");
                coordRawText = coordRawText.Replace("))", "");
                coordRawText = coordRawText.Replace(", ", ",");

                // Seperate coordinates to iterate through
                var coordsArray = coordRawText.Split(',');
                var coordsEnumerable = coordsArray.Select(coord => coord.Replace(" ", ","));

                // Build list of coordinates
                var coordsList = new List<CoordinateDto>();
                foreach (var coord in coordsEnumerable)
                {
                    var splt = coord.Split(',');
                    var x = double.Parse(splt[0]);
                    var y = double.Parse(splt[1]);

                    coordsList.Add(new CoordinateDto {X = x, Y = y});
                }

                myDto.Geometry = new GeometryDto
                {
                    Type =  "Polygon",
                    Coordinates = coordsList
                };

The above outputs "almost" what I want, but not exactly. Output is as shown below:

"geometry":{"type":"Polygon","coordinates":[{"x":319686.3666000003,"y":7363726.7955},{"x":319747.05190000031,"y":7363778.9233},{"x":319700.78849999979,"y":7363832.7814},{"x":319640.10329999961,"y":7363780.6536},{"x":319686.3666000003,"y":7363726.7955}]}

My DTOs are defined as follows:

[DataContract]
public class GeometryDto
{
    [DataMember]
    public string Type { get; set; }

    [DataMember]
    public List<CoordinateDto> Coordinates { get; set; }


}


[DataContract]
public class CoordinateDto
{
    [DataMember]
    public double X { get; set; }

    [DataMember]
    public double Y { get; set; }


}

I have tried to use tuples instead of coordinate class, but that simply inserted "item1" and "item2" property names instead of "x" and "y".

The only thing I haven't attempted yet is to create my own JSON Converter ?

Thanks in advance for help,

Kind regards,

Stefan

UPDATE ON SOLUTION

I reached a solution thanks to the selected answer here (from Dhanuka777) about multi-dimensional arrays, but for completeness in case it helps:

I had to create a new helper function (slightly modified version of Jon Skeet's Create Rectangular Array function from here: How to convert list of arrays into a multidimensional array )

Code solution as shown below:

/*

                Geometry Text Format from database:  POLYGON ((319686.3666000003 7363726.7955, 319747.05190000031 7363778.9233, 319700.78849999979 7363832.7814, 319640.10329999961 7363780.6536, 319686.3666000003 7363726.7955))

                And we want format:
                "geometry": {
                    "type": "Polygon",
                    "coordinates": [[
                        [319686.3666000003, 7363726.795],
                        [319747.0519000003, 7363778.9233],
                        [319700.78849999979, 7363832.7814],
                        [319640.10329999961, 7363780.6536],
                        [319686.3666000003, 7363726.795]
                    ]]
                }

                */


                // Strip out everything except the coordinates
                var coordRawText = myWkt.Replace("POLYGON ((", "");
                coordRawText = coordRawText.Replace("))", "");
                coordRawText = coordRawText.Replace(", ", ",");

                // Seperate coordinates to iterate through
                var coordsArray = coordRawText.Split(',');
                var coordsEnumerable = coordsArray.Select(coord => coord.Replace(" ", ","));

                // Build list of coordinates
                var coordsList = new List<double[,]>();
                foreach (var coord in coordsEnumerable)
                {
                    var splt = coord.Split(',');
                    var x = double.Parse(splt[0]);
                    var y = double.Parse(splt[1]);

                    coordsList.Add(new[,] {{ x, y }});
                }

                myDto.Geometry = new GeometryDto
                {
                    Type =  "Polygon",
                    Coordinates = CreateRectangularArray(coordsList)
                };

And a slightly modified version of Create Rectangular Array definition as below:

static T[,] CreateRectangularArray<T>(IList<T[,]> arrays)
        {
            // TODO: Validation and special-casing for arrays.Count == 0
            int minorLength = arrays[0].Length;
            T[,] ret = new T[arrays.Count, minorLength];
            for (int i = 0; i < arrays.Count; i++)
            {
                var array = arrays[i];
                if (array.Length != minorLength)
                {
                    throw new ArgumentException
                        ("All arrays must be the same length");
                }
                for (int j = 0; j < minorLength; j++)
                {
                    ret[i, j] = array[0, j];
                }
            }
            return ret;
        }

And the updated GeometryDto as follows:

[DataContract]
    public class GeometryDto
    {
        [DataMember]
        public string Type { get; set; }

        [DataMember]
        public double[,] Coordinates { get; set; }


    }

Web API will use Newtonsoft Json to serialize the objects in the required format.

like image 796
Stefan Zvonar Avatar asked Nov 09 '22 00:11

Stefan Zvonar


1 Answers

I would rather use Newtonsoft Json serializer to get this out put. Defininig coordinates as 2D array will do the trick.

public class GeometryDto
    {
        public string Type { get; set; }

        public double[,] coordinates { get; set; }            

    }

    class Program
    {
        static void Main()
        {
            var obj = new GeometryDto
            {
                Type = "Polygon",
                coordinates = new double[,] { { 319686.3666000003, 7363726.795 }, { 319747.0519000003, 7363778.9233 }, { 5.3434444, 6.423443 }, { 7.2343424234, 8.23424324 } }                     
            };
            var json = Newtonsoft.Json.JsonConvert.SerializeObject(obj);
            Console.WriteLine(json);
            Console.ReadKey();
        }
    }

Get the Nuget from here.

Output: {"Type":"Polygon","coordinates":[[319686.3666000003,7363726.795],[319747.05190000031,7363778.9233],...]}

like image 164
Dhanuka777 Avatar answered Nov 14 '22 23:11

Dhanuka777