locked
How to deserialize json to geometry data type RRS feed

  • Question

  • User2070555482 posted

    Hi every one , I must create an api services that the user can post an geometry (location) and retrieve it.

    I use PostgreSql as my database and Postgis extension. But now to make it simple I just created a sample app which my controller have a parameter type geometry and try to post it.

    First i installed a nugget for NTS 

    Install-Package Npgsql.EntityFrameworkCore.PostgreSQL.NetTopologySuite -Version 3.1.2

     Here are my sample model

    using NetTopologySuite.Geometries;
    
    namespace GeoLocationAPI.Models
    {
        public class GeoLocation
        {
            public string Name { get; set; }
    
            public Geometry Location  { get; set; }
    
        }
    }

    And here are my controller

    using GeoLocationAPI.Models;
    using Microsoft.AspNetCore.Mvc;
    
    namespace GeoLocationAPI.Controllers
    {
        [ApiController]
        [Route("[controller]")]
        public class WeatherForecastController : ControllerBase
        {
    
            [HttpPost]
            public IActionResult AddLocation(GeoLocation geoLocation)
            {
    
                return Ok();     
            }
        }
    }

    My swagger look like accepting the geometry data type

    {
      "name": "string",
      "location": {
        "userData": {},
        "srid": 4326
      }
    }

    but when i try to post a data i got an error like this

    System.NotSupportedException: Deserialization of reference types without parameterless constructor is not supported. Type 'NetTopologySuite.Geometries.Geometry'

    Monday, February 24, 2020 4:11 AM

Answers

All replies

  • User711641945 posted

    Hi TinVin727,

    As Deserialization behavior docs said:

    >Deserialization to reference types without a parameterless constructor isn't supported.

    `Geometry` contains constructor but does not contain parameterless constructor.

    This is a known github issue.And it has been added to .Net Core 5.0 milestone.

    Reference:

    https://github.com/dotnet/runtime/issues/30854

    To fix such issue,you could switch back to the previous default of using `Newtonsoft.Json`.

    Firstly,install the `Microsoft.AspNetCore.Mvc.NewtonsoftJson` NuGet package. Then in ConfigureServices() add a call to AddNewtonsoftJson() as follows:

    services.AddControllers()
              .AddNewtonsoftJson();

    Best Regards,

    Rena

    Tuesday, February 25, 2020 9:02 AM
  • User-474980206 posted

    You should use a library like 

    https://github.com/NetTopologySuite/NetTopologySuite.IO.GeoJSON

    to serialize and deserialize 

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, February 25, 2020 5:03 PM