HttpResponseMessage.HttpContent.ReadAsDefaultAsync<T>

Topics: Web Api
Jan 18, 2012 at 1:16 AM
I have this json
{
    "candidates": [
        {
            "address": "yada yada, 84109",
            "location": {
                "x": 4.92,
                "y": 44.02
            },
            "score": 82,
            "attributes": {}
        },
        {
            "address": "yada, 84109",
            "location": {
                "x": 42.6,
                "y": 46.82
            },
            "score": 44,
            "attributes": {}
        }
    ]
}

I'm doing 

r.Content.ReadAsOrDefaultAsync<DaoEsriGeocodeResult>()

I get a null response. My matching class for this json structure is 

public class DaoEsriGeocodeResult
    {
        public List<Candidates> candidates{ get; set; }
    }

    public class Candidates
    {
        public string address { get; set; }
        public Location location { get; set; }
        public int score { get; set; }
        public object attributes { get; set; }
    }

    public class Location
    {
        public double x { get; set; }
        public double y { get; set; }
    }


 Where am I going wrong?

Jan 18, 2012 at 1:18 AM
Edited Jan 18, 2012 at 1:18 AM

You shouldn't try to serialize "object". It won't know what to do with it.

 

Remove attributes, and see if it works.

Jan 18, 2012 at 1:19 AM

Also, try using a non asDefault async method. that way you will get a real error.

Jan 18, 2012 at 1:40 AM
Edited Jan 18, 2012 at 1:46 AM

with ReadAs I get

System.InvalidOperationException : No 'MediaTypeFormatter' is available to read an object of type 'DaoEsriGeocodeResult' with the media type 'text/plain'.

The service must be sending json with the wrong content-type.

I do have this class though:

   public class EsriJsonResponseFormatter: JsonMediaTypeFormatter
    {
        public EsriJsonResponseFormatter()
        {
            SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/plain"));
        }
    }

 

yet I don't use it anywhere. 

using it 

r.Content.ReadAsAsync<DaoEsriGeocodeResult>(new MediaTypeFormatter[] { new EsriJsonResponseFormatter() });

fixes the issue.

 

Thanks!

Jan 18, 2012 at 1:43 AM
Edited Jan 18, 2012 at 1:43 AM

You would need to apply that formatter to your configuration.

Do you have a class that inherits from WebApiConfiguration that you applied?

It would look something like this in the global.asax:

 

            RouteTable.Routes.SetDefaultHttpConfiguration(new AuthenticationHttpConfiguration());

Then in the constructor of the configuration class you can do 

 

 

            Formatters.Add(new EsriJsonResponseFormatter());