2

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?

7
  • 1
    return Json(test)? Commented Apr 24, 2017 at 9:25
  • @UweKeim I cannot do this because I want add custom ContractResolver to json Serialize method Commented Apr 24, 2017 at 9:26
  • 1
    That is Visual Studio's formatting probably. Test it by printing it to a file or into the console. @UweKeim read the question again. That's not his problem. Commented Apr 24, 2017 at 9:27
  • @Mafii I tested it with Postman application Commented Apr 24, 2017 at 9:28
  • @mkul look into Ok(). I don't know what it does exactly, but it escapes the string. Do you have the source of the OK function? Commented Apr 24, 2017 at 9:30

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.