简体   繁体   中英

MVC WEB API Controller C# JSON Deserialize not working

I have been struggling with my first c# project. This is a web api controller that will receive a post from AngularJS. The post is coming across but appears to have an extra set of brackets in the JSON object (right click/copy value in vs 2015) . I have tried various methods but everytime I deserialize the JSON object I get null values.

public class LocationsTestController : ApiController
{

    [System.Web.Http.HttpPost]
    [Route("")]

    public IHttpActionResult Post(object json)
    {

        string sjson = json.ToString();

        Coords oCoords = JsonConvert.DeserializeObject<Coords>(sjson);

        DBEntities db = new DBEntities();
        db.spUpdateLocation(User.Identity.Name, oCoords.latitude.ToString(), oCoords.longitude.ToString());
        db.SaveChanges();

        return Ok(oCoords.latitude); //return trash data for now
    }

}

Here is my JSON copied from the the object received by the post.

{{
  "coords": {
    "latitude": 43.445969749565833,
    "longitude": -80.484091512936885,
    "altitude": 100,
    "accuracy": 150,
    "altitudeAccuracy": 80,
    "heading": 38,
    "speed": 25
  },
  "timestamp": 1442113213418
}}

I have tried mapping to the entity framework, but problem is I need to add the authenticated username to the json object as I don't want to trust what is being passed to the API.

Any help would be much appreciated.

There might be some issues with the way you are posting from client side. It's hard to check without the client code and what exactly is coming over network (in fiddler for example).

Generally the web api should be able to get the object directly without you deserializing it. So, if the client is posting proper json, this should work

public IHttpActionResult Post(Coords oCoords)
{
    //use oCoords directly
}

If that doesn't work, try changing your web api method to receive string rather than an object, and deserialize that string.

public IHttpActionResult Post(string jsonString)
{
    Coords oCoords = JsonConvert.DeserializeObject<Coords>(jsonString);

    //rest of the code
}

If you still have double braces, you can do this before you deserialize

jsonString = jsonString.Replace("{{", "{").Replace("}}", "}");

But, obviously, this is not the correct fix. The issue still remains somewhere.

Try to receive a model instead of plain string in your WebApi method:

public class CoordsItemModel
{
    public double latitude { get; set; }
    public double longitude { get; set; }
    public int altitude { get; set; }
    public int accuracy { get; set; }
    public int altitudeAccuracy { get; set; }
    public int heading { get; set; }
    public int speed { get; set; }
}

public class CoordsModel
{
    public CoordsItemModel coords { get; set; }
    public long timestamp { get; set; }
}

[System.Web.Http.HttpPost]
[Route("")]
public IHttpActionResult Post(CoordsModel model)
{
    DBEntities db = new DBEntities();
    db.spUpdateLocation(User.Identity.Name, model.coords.latitude.ToString(), model.coords.longitude.ToString());
    db.SaveChanges();

    return Ok(model.coords.latitude.ToString()); //return trash data for now
}
Use It.
 public class coordsSample
        {
            public string latitude { get; set; }
            public string longitude { get; set; }
            public int altitude { get; set; }
            public int accuracy { get; set; }
            public int altitudeAccuracy { get; set; }
            public int heading { get; set; }

            public int speed { get; set; }
        }

        public class coords1
        {
            public coordsSample coords { get; set; }
            public long timestamp { get; set; }
        }

  static void Main(string[] args)
        {
            var jsonFormat = @"[{""timestamp"":""1442113213418"",""coords"":{
""latitude"":""43.445969749565833"",""longitude"":""-80.484091512936885"",""altitude"":""100"",""accuracy"":""150""
,""altitudeAccuracy"":""80"",""heading"":""38"",""speed"":""25""}}]";
            var result = JsonConvert.DeserializeObject<coords1>(jsonFormat.Substring(1).Substring(0, jsonFormat.Length - 2));

            Console.WriteLine(result.coords.latitude);
            Console.WriteLine(result.coords.longitude);
}

Try Like that it will help for you.because those coords you take in json it trated as a properties so for that you need to create a new class and assign this properties in inside it.Thanks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM