Search code examples
c#jsonasp.net-web-apiasp.net-apicontroller

JSON passed to ApiController doesn't deserialize string values


I'm trying to pass a JSON array to an ApiController but the string values aren't deserializing (they are set to null values). The strange thing is that I still get the correct number of elements.

A have an ApiController:

[RoutePrefix("api/language")]
public class LanguagePairApiController : ApiController

With a post method:

// POST: api/language/create
[HttpPost]
[Route("create")]
public string Create([FromBody]LanguagePair[] languagePairs)

I'm sending JSON to it:

[
    {"Key":"Test","Value":"Test","Version":"1.0"},
    {"Key":"Areyousure","Value":"Are you sure?","Version":"1.0"},
    {"Key":"File","Value":"File","Version":"1.0"}
]

And this is the class I'm trying to map it to:

public class LanguagePair
{
    public string Key { get; set; }
    public string Value { get; set; }
    public string Version { get; set; }
}

But the string values are coming through as null:

enter image description here

What am I missing?
EDIT: I've figured out one answer to this and posted it below. But I'm still looking for a better answer...


Solution

  • I figured it out. I needed to decorate the class with DataContract and DataMember attributes:

    {
        [DataContract]
        public class LanguagePair
        {
            [DataMember]
            public string Key { get; set; }
            [DataMember]
            public string Value { get; set; }
            [DataMember]
            public string Version { get; set; }
        }
    }