0

When deserializing a request I get a non-null but empty dictionary.

Object I want to post:

public class Data
{
    public IDictionary<string, object> Dictionary { get; set; }
}

Here is the body I send with my request:

{"Dictionary":{"key1":"value1","foo":"bar"}}

The built-in serializer creates a Data object with an empty Dictionary. The Newtonsoft serializer behaves how I want. So after some googling I changed the service contract to accept a Stream rather than a Data.

using Newtonsoft.Json;

[ServiceContract]
interface IMyServiceContract
{
    [OperationContract]
    [WebInvoke(
        Method = "POST",
        UriTemplate = "data",
        RequestFormat = WebMessageFormat.Json)]
    void PostData(Stream body);
}

class MyServiceContract : IMyServiceContract
{
    void PostData(Stream body)
    {
        using (var reader = new StreamReader(body))
            json = reader.ReadToEnd();
        data = JsonConvert.DeserializeObject<Data>(json);
        // ...
    }
}

The main problem here is that the request is no longer accepted if I specify the header Content-Type: application/json, which I obviously want, but it would also be nice if the method signature mentioned Data.

How can I specify a custom deserializer for my service? Or, if not possible, make the current solution work even if Content-Type is specified?

Mizipzor
  • 51,151
  • 22
  • 97
  • 138
  • I have no problems while deserializing any objects posted to web service as a `string` parameter. Using either `Stream` or custom JSON serializer looks more like a hack but not a solution. – Yeldar Kurmangaliyev Jun 02 '15 at 10:08
  • If I change the type from `Stream` to `string` I get: `Additional information: End element 'root' from namespace '' expected. Found element 'Dictionary' from namespace ''.` – Mizipzor Jun 02 '15 at 10:14
  • It tries to deserialize something else except for your `Dictionary` and there is a reason for it. It looks like you have posted not the whole `Data` class declaration. Could you provide it? Make sure it's not a `Data` class from another namespace :) – Yeldar Kurmangaliyev Jun 02 '15 at 10:20
  • That is actually the entire `Data` object, I stripped everything away trying to reproduce for Stackoverflow. I also tried rename the class to Data2 just to make sure it wasn't something else that was picked up. – Mizipzor Jun 02 '15 at 10:43

0 Answers0