title: Serialize data from PostGIS to JSON
body: <p>I'm working on a .NET Core REST service which will have a controller that will send  geometry data back a GeoJson so I can show it on my Leaflet map.</p>
  
  <p>I'm having trouble converting my class to JSON.</p>
  
  <p>I've tried this: </p>
  
  <pre><code>StringBuilder sb = new StringBuilder();
  JsonTextWriter writer = new JsonTextWriter(new StringWriter(sb));
  var jsonSerializer = GeoJsonSerializer.Create(new JsonSerializerSettings()
      {NullValueHandling = NullValueHandling.Ignore});
  jsonSerializer.Serialize(writer, _context.Locations);
  writer.Flush();
  return Ok(sb.ToString());
  </code></pre>
  
  <p>But then I get this error </p>
  
  <pre><code>Self referencing loop detected for property 'CoordinateValue' with type 'GeoAPI.Geometries.Coordinate'
  </code></pre>
  
  <p>I've been looking for examples and reading docs all day but can't get it to work.</p>
  
  <p>The class I need to serialize:</p>
  
  <pre><code>public class SobekLocation
  {
      public int Id { get; set; }
      public string LocationId { get; set; }
      public bool Use { get; set; }
      public Point Location { get; set; }
  }
  </code></pre>
  
  <p>Any suggestions are much appreciated.</p>
  
  <p><strong>Edit</strong>:</p>
  
  <p>I'm making my own featurecollection and am trying to serialize that. It is doing something but it is not valid GeoJSON.</p>
  
  <pre><code>    public FeatureCollection GetLocationsAsFeatureCollection()
      {
          var featureCollection = new FeatureCollection();
          foreach (var location in GetLocations().Take(5))
          {
              var attr = new AttributesTable
              {
                  {"Id", location.Id},
                  {"Use", location.Use},
                  {"LocationId", location.LocationId}
              };
  
              var feature = new Feature(location.Location, attr);
              featureCollection.Add(feature);
          }
  
          return featureCollection;
      }
  </code></pre>
  
  <p>And de serialization part:</p>
  
  <pre><code>var fc = _service.GetLocationsAsFeatureCollection();
  var sb = new StringBuilder();
  var jsonSerializer = JsonSerializer.Create(new JsonSerializerSettings
  {
      // To prevent the Self referencing loop error:
      ReferenceLoopHandling = ReferenceLoopHandling.Ignore 
  });
  
  using (var sw = new StringWriter(sb))
  {
      jsonSerializer.Serialize(sw, fc);
  }
  
  return Ok(sb.ToString());
  </code></pre>
  
  <p>The serialized data:</p>
  
  <pre><code>{  
     "Features":[  
        {  
           "Geometry":{  
              "CoordinateSequence":{  
                 "Dimension":3,
                 "Ordinates":7,
                 "Count":1
              },
              "Coordinates":[  
                 {  
                    "X":191390.015,
                    "Y":523064.716597462,
                    "Z":"NaN"
                 }
              ],
              "NumPoints":1,
              "IsEmpty":false,
              "Dimension":0,
              "BoundaryDimension":-1,
              "X":191390.015,
              "Y":523064.716597462,
              "Coordinate":{  
                 "X":191390.015,
                 "Y":523064.716597462,
                 "Z":"NaN"
              },
              "GeometryType":"Point",
              "OgcGeometryType":1,
              "Boundary":[  
  
              ],
              "Z":"NaN",
              "M":"NaN",
              "Factory":{  
                 "PrecisionModel":{  
                    "IsFloating":true,
                    "MaximumSignificantDigits":16,
                    "Scale":0,
                    "PrecisionModelType":0,
                    "OffsetX":0,
                    "OffsetY":0
                 },
                 "CoordinateSequenceFactory":{  
                    "Ordinates":7
                 },
                 "SRID":28992
              },
              "UserData":null,
              "SRID":28992,
              "PrecisionModel":{  
                 "IsFloating":true,
                 "MaximumSignificantDigits":16,
                 "Scale":0,
                 "PrecisionModelType":0,
                 "OffsetX":0,
                 "OffsetY":0
              },
              "NumGeometries":1,
              "IsSimple":true,
              "IsValid":true,
              "Area":0,
              "Length":0,
              "EnvelopeInternal":{  
                 "IsNull":false,
                 "Width":0,
                 "Height":0,
                 "MinX":191390.015,
                 "MaxX":191390.015,
                 "MinY":523064.716597462,
                 "MaxY":523064.716597462,
                 "Area":0,
                 "MinExtent":0,
                 "MaxExtent":0,
                 "Centre":{  
                    "X":191390.015,
                    "Y":523064.716597462,
                    "Z":"NaN"
                 }
              },
              "IsRectangle":false
           },
           "Attributes":[  
              {  
                 "Key":"Id",
                 "Value":1
              },
              {  
                 "Key":"Use",
                 "Value":false
              },
              {  
                 "Key":"LocationId",
                 "Value":"KNP_1"
              }
           ],
           "BoundingBox":null
        }
     ],
     "Type":"FeatureCollection",
     "CRS":null,
     "Count":5,
     "BoundingBox":null
  }
  </code></pre>
  
  <p>As you can see all properties start with an uppercase but they should be in lowercase. And after changing the properties manually geojsonlint.com reports: <code>GeoJSON features must have a type=feature member</code></p>
  
  <p><strong>Edit2</strong>:</p>
  
  <p>I've made some progress. I'm using the GeoJSON.Net package now and I can now create valid GeoJSON accordin to <a href="http://geojsonlint.com/" rel="nofollow noreferrer">http://geojsonlint.com/</a>. But still my Leaflet map is complaining about invalid GeoJSON so the map is still not showing anything ;)</p>
  
  <p>Here's my new converter:</p>
  
  <pre><code>    public GeoJSON.Net.Feature.FeatureCollection GetLocationsAsGeoJsonFeatureCollection()
      {
          var featureCollection = new GeoJSON.Net.Feature.FeatureCollection();
          foreach (var location in GetLocations())
          {
              var attr = new Dictionary&lt;string, object&gt;()
              {
                  {"Id", location.Id},
                  {"Use", location.Use},
                  {"LocationId", location.LocationId}
              };
  
              var position = new Position(location.Location.Coordinate.X, location.Location.Coordinate.Y);
              var geom = new GeoJSON.Net.Geometry.Point(position);
              var feature = new GeoJSON.Net.Feature.Feature(geom, attr, location.Id.ToString());
              featureCollection.Features.Add(feature);
          }
  
          return featureCollection;
      }
  </code></pre>
  
  <p>And the GeoJSON it produces:</p>
  
  <pre><code>{  
     "type":"FeatureCollection",
     "features":[  
        {  
           "type":"Feature",
           "id":"1",
           "geometry":{  
              "type":"Point",
              "coordinates":[  
                 523064.716597462,
                 191390.015
              ]
           },
           "properties":{  
              "id":1,
              "use":false,
              "locationId":"KNP_1"
           }
        },
        {  
           "type":"Feature",
           "id":"2",
           "geometry":{  
              "type":"Point",
              "coordinates":[  
                 519349.860113963,
                 170162.249352578
              ]
           },
           "properties":{  
              "id":2,
              "use":false,
              "locationId":"CP_6"
           }
        },
        {  
           "type":"Feature",
           "id":"3",
           "geometry":{  
              "type":"Point",
              "coordinates":[  
                 519952.507022603,
                 170402.383673312
              ]
           },
           "properties":{  
              "id":3,
              "use":false,
              "locationId":"CP_UR_5_1"
           }
        },
        {  
           "type":"Feature",
           "id":"4",
           "geometry":{  
              "type":"Point",
              "coordinates":[  
                 519948.062527202,
                 170582.612655391
              ]
           },
           "properties":{  
              "id":4,
              "use":false,
              "locationId":"CP_UR_6_1"
           }
        },
        {  
           "type":"Feature",
           "id":"5",
           "geometry":{  
              "type":"Point",
              "coordinates":[  
                 519902.432252114,
                 170602.894875503
              ]
           },
           "properties":{  
              "id":5,
              "use":false,
              "locationId":"CP_UR_6_2"
           }
        }
     ]
  }
  </code></pre>
  
  <p>This is my code for Leaflet:</p>
  
  <pre><code>L.geoJson('http://localhost:5000/api/data/',
    {
      attribution: 'Mine'
    }
  ).addTo(map);
  </code></pre>
  
  <p>I'm still looking for advice how to easily plot my PostGIS data on a Leaflet map.</p>