1

I am doing a C# web Api Method and the Consumer.

Firstly, the method retrieve a class instance and the Consumer call it like this, and parse it to a Class called R

HttpResponseMessage response = client.PostAsJsonAsync(url, param).Result;
R value = await response.Content.ReadAsJsonAsync<R>();

Now, I need to retrieve from my Api, only the class properties it have data. For that reason it parse the class instance to Json, as i asked here, using

 string jsonIgnoreNullValues = JsonConvert.SerializeObject(response, Formatting.Indented, new JsonSerializerSettings
                {
                    NullValueHandling = NullValueHandling.Ignore
                });

My web Method definition is simple

   public IHttpActionResult Newemployee([FromBody] RequestManual items)
    {
         ResponseManual response = Service.Newemployee(items.Datos);
         //Before
          return Ok(response);

          //Now
           string jsonIgnoreNullValues = JsonConvert.SerializeObject(response, Formatting.Indented, new JsonSerializerSettings
                {
                    NullValueHandling = NullValueHandling.Ignore
                });
          return Ok(jsonIgnoreNullValues);
    }

}

.NET automatically Serialize to Json in the response, When i Serialize the response to avoid null properties, the respose is getting serialized twice...

How can avoid this, or how can I read this?

Thanks

0

1 Answer 1

2

Configure the formatter at startup. Under the hood Web API is using Json.Net framework, so you will have access to the same serialization settings

WebApiConfig.cs

var jsonFormatter = config.Formatters.JsonFormatter
jsonFormatter.SerializerSettings.NullValueHandling = NullValueHandling.Ignore

That way you can use the original code as before

[HttpPost]
public IHttpActionResult Newemployee([FromBody] RequestManual items) {
    if(ModelState.IsValid) {
        var response = Service.Newemployee(items.Datos);
        return Ok(response);
    }
    return BadRequest(ModelState);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.