1

I have the following method:

[HttpPost]
[AjaxOnly]
public JsonResult ValidateInput(string text)
{
    return new EmptyJsonResult();
}

/// <summary>
/// returns a JSON result that is marked as being empty.
/// </summary>
public sealed class EmptyJsonResult : JsonResult
{
    public EmptyJsonResult()
    {
        Data = new JsonResultData
        {
            Empty = true
        };
    }
}

public class JsonResultData
{
    public bool Empty { get; set; }
    public string[] Errors { get; set; }
}

I expected this to return {"Empty":true} to the browser, but it returns {"Empty":true,"Errors":null} instead.

Is there any attribute or something I can set in order to avoid returning nulls on objects I didn't populate?

bevacqua
  • 47,502
  • 56
  • 171
  • 285
  • and what value do you want to populate? you can always write your own getter for every object, however null is ok – alexsuslin Feb 20 '12 at 16:07
  • may be you should look at the source code and see if you can change something.. here is a SO question that delves around that area: http://stackoverflow.com/questions/8833961/serializing-null-in-json-net – Baz1nga Feb 20 '12 at 16:18
  • How would I implement `NullValueHandling.Ignore` here? – bevacqua Feb 20 '12 at 16:21

2 Answers2

1

Does it make any difference for you if you simply return an anon object?

    public EmptyJsonResult()
    {
    Data = new
        {
            Empty = true
        };
    }
peterfoldi
  • 7,451
  • 5
  • 21
  • 19
0

I don't see a problem returning null, but if you need to accomplish your goal, have an interface called JsonResultData and two classes which implement it. One has all of the attributes you need to return and the second only has Empty in it.

John Koerner
  • 37,428
  • 8
  • 84
  • 134