Home Deserializing Jsonobject in mvc webapi
Reply: 2

Deserializing Jsonobject in mvc webapi

Lautaro
1#
Lautaro Published in 2018-01-12 14:05:27Z

Im trying to send a jSon object to a WebApiController and deserialize it to an object but it just gives me an empty object with zero and null.

Id much rather do model binding though but that does not seem to work in Webappi like it does with AJAX call to a normal MVC controller ?

Javascript (jQuery)

var data = {
                    siffra : 23,
                    text : "Meddelande från andra sidan!"
                }

                $.ajax({

                    url: "api/Stuff/PostStuff",
                    method: "POST",
                    data: JSON.stringify(data),
                    success: function (result) {
                        console.log("SUCESS: " + result);
                    },
                    error: function (data) {
                        console.log("error: " + data.responseText);
                    }
                });

WebApiController method

 public string PostStuff(JObject jsonObject)
    {
        Stuff stuff  = JsonConvert.DeserializeObject<Stuff>(jsonObject.ToString());
        return "thanks";

    }

    public class Stuff
    {
        public int siffra;
        public string text;     
    }

JObject before deserialization: {"{\"siffra\":23,\"text\":\"Meddelande från andra sidan!\"}": ""}

garret
2#
garret Reply to 2018-01-12 14:22:17Z

Insted of JObject use Stuff model

public string PostStuff(Stuff stuff)
{
    return "thanks";

}

WebApi should serilize it automaticly.

Edit

And make sure that ajax send proper json like this one:

{
    "siffra" : 23,
    "text" : "Meddelande från andra sidan!"
}

Edit 2 Try this call

var data = {
                siffra : 23,
                text : "Meddelande från andra sidan!"
            }

            $.ajax({

                url: "api/Stuff/PostStuff",
                method: "POST",
                data: data,
                success: function (result) {
                    console.log("SUCESS: " + result);
                },
                error: function (data) {
                    console.log("error: " + data.responseText);
                }
            });
Richard
3#
Richard Reply to 2018-01-12 14:13:52Z
 {"{\"siffra\":23,\"text\":\"Meddelande från andra sidan!\"}": ""}

That is a JSON object with a single property named {\"siffra\":23,\"text\":\"Meddelande från andra sidan!\"} with the empty string for its value. This is nothing like the Stuff type.

Which does not match the quoted JS code so you've not included something.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.308697 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO