mkul
mkul

Reputation: 810

How return json object instead of string in json.net?

I want to implement custom json.net serialize method (null value handling, custom ContractResolver etc.), but when I tried with JsonConvert.SerializeObject() I always get string in output instead of formatted json object. Here is my code:

public class Card
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

    public class TestController : ApiController
    {
        [HttpGet]
        [Route("api/Test")]
        public IHttpActionResult Test()
        {
            var test = new Card()
            {
                Id = 2,
                Name = "test card"
            };

            JsonSerializerSettings settings = new JsonSerializerSettings
            {
                NullValueHandling = NullValueHandling.Ignore,
                Formatting = Formatting.Indented
            };
            var result = JsonConvert.SerializeObject(test, settings);

            return Ok(result);
        }
    }

It returns "{\r\n \"Id\": 2,\r\n \"Name\": \"test card\"\r\n}"

When I return object (return Ok(test);) in api controller I'll get correct formatted json

{
  "Id": 2,
  "Name": "test card"
}

How I can return json object in api controller with custom implementation of serialize?

Upvotes: 2

Views: 5699

Answers (1)

mkul
mkul

Reputation: 810

It was configuration issue. For attach custom serializer options to global web api configuration, just change WebApiConfig as follow:

config.Formatters.JsonFormatter.S‌​erializerSettings = new JsonSerializerSettings
            {
                NullValueHandling = NullValueHandling.Ignore,
                Formatting = Formatting.Indented
            };

And pass object to return line - serialization will be done automatically

Upvotes: 1

Related Questions