Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON.NET Parser *seems* to be double serializing my objects

My problem is this:

This is the response being sent back from my WebAPI controller.

"[
   [
      {\"id\":\"identifier\"},
      {\"name\":\"foobar\"}
   ]
]"

Notice that the response is wrapped in quotations and all of the embedded quotations are escaped. This is obviously a problem. Are there any settings I can provide to the JSON.NET Serializer to prevent this from occurring?

Edit

As p.s.w.g guessed in his response, I was using JSON.NET's

JsonConvert.SerializeObject(instance)

to perform my serialization.

I did this because as I was building out my custom Converters, I had included them in the JsonConvert.DefaultSettings within my WepApiConfig (and I obviously thought this would not be a problem)

I had previously tried to swap the return type of my HttpGets to "my object type" and the response was a json representation of my object's ToString() method...which let me know that serialization was not passing through my converters.

Changing the return type of my HttpGets from string to "my object type" and plugging those converters straight into WebAPi's default HttpConfiguration did the trick.

config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new FooConverter());
config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new BarConverter());

Easy peasy.

like image 211
K. Alan Bates Avatar asked Aug 28 '14 22:08

K. Alan Bates


1 Answers

You probably have something like this:

public string GetFoobars()
{
    var foobars = ...
    return JsonConvert.SerializeObject(foobars);
}

In this case, you're serializing the object into string with Json.NET, then by returning the result as a string, the API controller will serialize the string as a JavaScript string literal—which will cause the string to be wrapped in double quotes and cause any other special characters inside the string to escaped with a backslash.

The solution is to simply return the objects by themselves:

public IEnumerable<Foobar> GetFoobars()
{
    var foobars = ...
    return foobars;
}

This will cause the API controller to serialize the objects using it's default settings, meaning it will serialize the result as XML or JSON depending on the parameters passed in from the client.

Further Reading

  • JSON and XML Serialization in ASP.NET Web API
like image 173
p.s.w.g Avatar answered Sep 23 '22 21:09

p.s.w.g