5

How to render null string properties as empty strings in ASP.NET MVC4 Web API v.1 in json result? WebAPI renders them as

"myproperty": null

how to render this as

"myproperty": ""

controller is

public class Customer {
   public string myproperty { get; set; }
   }

    public class CustomersController : ApiController
    {
        public HttpResponseMessage Get()
        {
            var cust = new Customer();
            return Request.CreateResponse(HttpStatusCode.OK,
               new { customers = cust.ToArray() });
        }
     }

object are nested and contain lot of string properties. Setting them all to empty strings in constructor seems ugly. API caller needs empty strings or 0 for decimals, it does not like null constant in any value.

10
  • 2
    That's a completely ridiculous requirement. Null and empty strings are 2 completely different notions and are JSON serialized differently. Why would you want to mix those notions? You could of course achieve that by writing a custom ValueProvider for JSON.NET but I don't even want to show an example of that as this seems completely useless thing to do. And most importantly a very wrong thing to do. Commented Nov 24, 2013 at 20:52
  • 3
    What's the reason about judging requirements? He wants null string to be treated as empty strings, that's it. We don't have enough contest to say if it's good or not. You don't like it? Care. Commented Nov 24, 2013 at 20:56
  • Just mentioning that those requirements do not make any reasonable sense. Sometimes people are forced to write completely stupid and wrong code just because they are obeying requirements that are completely ridiculous. Instead of explaining the people that enforced those requirements how wrong they are. That's usually how we end up with hacks and completely crapped up software. Commented Nov 24, 2013 at 20:58
  • 1
    @Darin Dimitrov I need to create api for existing javascript application. I looked into existing response and all unassigned string values contain empty strings. Currently my API returns null values but application does not work correctly. So I thought to try empty strings like existing API provides to it. Javascript application is complex and difficult to understand or refactor. Commented Nov 24, 2013 at 21:00
  • 2
    My 2cents on the issue: When you are dealing with APIs, you have no control over existing clients (so fix the client javascript is mostly not an option), while backward compatibility is really important and should be enforced. Setting default values for properties is not a hack nor crappy, that's why there's an implementation to do it within the framework without writing our own value providers or 'hacky' code. I still agree that it's better if can be avoided on, for example, new developments. Commented Feb 20, 2014 at 16:57

4 Answers 4

8

you can decorate your properties like this :

[JsonProperty(DefaultValueHandling = DefaultValueHandling.Populate)]
[DefaultValue("")]
public string myproperty{ get; set; }

Note that you can set the default value handling to populate in a global config like this:

GlobalConfiguration
.Configuration
.Formatters
.JsonFormatter
.SerializerSettings
.DefaultValueHandling = Newtonsoft.Json.DefaultValueHandling.Populate;

So, you don't need to decorate it to every property. You will only need to use the DefaultValue.

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

Comments

2
public class Customer {
   private string _myproperty = String.Empty;
   public string myproperty 
   { 
      get { return _myproperty; }; 
      set { _myproperty = value ?? String.Empty; } 
   }
}

1 Comment

Thank you. Actually there are 30 properties from which some are assigned with null values. Using your answer requires to write if statement for every property before return. Maybe it is possible to create value provider which converts null to empty string and pass it to CreateResponse method to use it or use JSon.NET or other serializer which allows this ?
0

i give little overhead but solve my problem

DataTable dt = (new tst()).Gettable();
            string s = string.Empty;
            s = Newtonsoft.Json.JsonConvert.SerializeObject(dt);
           s= s.Replace("null", "\"\"");
            Object obj = Newtonsoft.Json.JsonConvert.DeserializeObject(s);
            return Ok(obj);

Comments

-7

As default web api works like this... you don't need to change

1 Comment

It does not work like this. As described in question, it renders null string values as null in json

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.