My C # .net server web API cannot deserialize JSON object

This code of my client

var sayeed = { firstname: "Sayeed", surname: "Alquiaty" };
alert(JSON.stringify({ person: sayeed }));
$.ajax({
    url: "api/parent",
    type: "POST",
    contentType: "application/json; charset=utf-8",
    data: JSON.stringify({ person: sayeed }),
    success: function(response) {
        response ? alert("It worked!") : alert("It didn't work.");
    }
});

      

Server side

public class Person {
    public string Firstname { get; set; }
    public string Surname { get; set; }
}

//Here I am able to receive object but is is not FirstName = null and Surname = null
// POST api/parent
public bool PostParent(Person person) {
    return person != null;
}

      

This way the client gets a success message, but in fact the JSON Object is not Deserialize

I tried another method like using JObject, but it's an explicit Json object, I mean it converts the client object as a key and then adds: "". This is not what I want.

+3


source to share


3 answers


There are several problems with the code:

  • deserialization is case sensitive, so JS side properties should have the same case as server side properties
  • You need to pass the person object as a parameter directly, not be included as a property of the person

    object
  • although it usually won't hurt, you don't need to plane the object. jQuery ajax

    will do this automatically for you


As for 1, you can set up a Web API serializer to convert the PascalCase backend to camelCase client side and vice versa, but you still need to consider this when converting property names between client and server side:

var jsonformatter
  = GlobalConfiguration.Configuration.Formatters.JsonFormatter;

jsonformatter.SerializerSettings.ContractResolver
  = new CamelCasePropertyNamesContractResolver();

      

+1


source


Thank you all for helping me solve this problem. But I could spot an error in my server side code, this is exactly this

config.Formatters.JsonFormatter.UseDataContractJsonSerializer = true;
config.Formatters.JsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
config.Formatters.XmlFormatter.UseXmlSerializer = false;

      



So now I commented out the above config setting and every thing started working fine. But it took me 2 days to actually figure out the real reason (presumably)

0


source


Sorry for forgetting to mention that I made a small change to PostParent (JObject result) so the result can get the deserialized JSON object correctly. Then I can create a human object from it. Hope this is helpful

0


source







All Articles