Casey Crookston
Casey Crookston

Reputation: 13955

API returns valid JSON in code, but invalid JSON in browser

I've got a very simply API method that looks like this:

public string Get(int id)
{
    Doors door = (Doors)Repository<Doors>.Get(id);
    string d = JsonConvert.SerializeObject(door);
    return d;
}

With this in the WebAPIConfig:

config.Formatters.JsonFormatter.SupportedMediaTypes
    .Add(new MediaTypeHeaderValue("text/html"));

When I put a breakpoint on d, I get this:

{"DoorSys":100000,"DoorName":"Door 1 - Out","DoorID":"Door # 01 (Out)","LocationSys":-1,"StatusSys":100001,"OrganizationSys":805408}

That's all good. But by the time it shows up in the browser, it looks like this:

"{\"DoorSys\":100000,\"DoorName\":\"Door 1 - Out\",\"DoorID\":\"Door # 01 (Out)\",\"LocationSys\":-1,\"StatusSys\":100001,\"OrganizationSys\":805408}"

And if I put what is returned in the browser into a JSON formatter, it of course doesn't like it. At all.

What (if anything?) am I doing wrong?

EDIT:

Based on the answer by L.B, I am doing this instead:

public Doors Get(int id)
{
    Doors door = (Doors)Repository<Doors>.Get(id);
    return door;
}

That works!

Upvotes: 1

Views: 209

Answers (1)

L.B
L.B

Reputation: 116118

You are double-serializing the door object. Declare your Get method as

public Doors Get(int id)

Upvotes: 4

Related Questions