Baldy
Baldy

Reputation: 3659

JSON model binding with XML Serialisation attributes in Web API

I have an API controller with the following action signature...

[HttpPost]
public HttpResponseMessage DoSearch(SearchParameters parameters)

SearchParameters is not something i can modify, and the decompiled source looks like this...

 [DebuggerStepThrough]
  [XmlRoot("SearchData", IsNullable = false, Namespace = "http://company.com/some/namespace/v1")]
  [GeneratedCode("xsd", "2.0.50727.3038")]
  [DesignerCategory("code")]
  [XmlType(Namespace = "http://company.com/some/namespace/v1")]
  [Serializable]
  public class SearchParameters
  {
    private string[] _searchCodes;

    [XmlArrayItem("SearchCode", IsNullable = false)]
    public string[] SearchCodes
    {
      get
      {
        return this._searchCodes;
      }
      set
      {
        this._searchCodes = value;
      }
    }
  }

I can call the endpoint successfully with an XML payload, but cannot get JSON to work at all. The SearchCodes property is always null.

If i replace the SearchParameters Type with a POCO that has none of the Xml Serialisation attributes on it, it works fine with JSON. This led me to think that the JsonMediaTypeFormatter is unable to match up the property correctly due to the xml serialisation attributes (even though this shouldnt matter, as its JSON, not XML right?). I changed the JsonFormatter to use the DataContract Serializer, but that has made no difference.

httpConfiguration.Formatters.JsonFormatter.UseDataContractJsonSerializer = true;

I tried crafting different structures of JSON to see if i could 'help' it understand, but none of these work either...

{
    "SearchData": {
        "SearchCodes": {
            "SearchCode": [
                "SYAA113F",
                "N0TEXI5T",
                "SYAA112C"
            ]
        }
    }
}


{
    "SearchCodes": {
        "SearchCode": [
            "SYAA113F",
            "N0TEXI5T",
            "SYAA112C"
        ]
    }
}

{
    "SearchCodes":  [
            "SYAA113F",
            "N0TEXI5T",
            "SYAA112C"
        ]
}


{
    "SearchData": {
        "SearchCode": [
            "SYAA113F",
            "N0TEXI5T",
            "SYAA112C"
        ]
    }
}


{
    "SearchCode": [
        "SYAA113F",
        "N0TEXI5T",
        "SYAA112C"
    ]
}

{
    "SearchCodes":  [
            { "SearchCode" : "SYAA113F" },
            { "SearchCode" : "SYAA113F" },
            { "SearchCode" : "SYAA113F" }
        ]
}

How can i debug this further? and what am i missing? What is causing the JSON media formatter to behave differently due to the XML attributes?

Upvotes: 1

Views: 313

Answers (1)

Post this JSON and see.

{"_searchCodes":[
        "SYAA113F",
        "N0TEXI5T",
        "SYAA112C"]
}

Remember to set Content-Type: application/json.

Upvotes: 1

Related Questions