简体   繁体   English

返回json结果并将null转换为空字符串

[英]Returns json result and convert null to empty string

I have an action that returns json result, but some of the attributes are null and I want to convert them to empty strings instead. 我有一个返回json结果的动作,但有些属性为null,我想将它们转换为空字符串。 I heard I can use DefaultValue("") , but it's still returning null instead of empty string. 我听说我可以使用DefaultValue("") ,但它仍然返回null而不是空字符串。

The action is: 行动是:

[HttpGet]
public ActionResult GetResults(string date)
{
    var data= GetData();  // returns List<Foo>
    var json = Json(data, JsonRequestBehavior.AllowGet);
    return json;
}

The Foo class is: Foo类是:

public class Foo
{
    public string Bar1;

    [DefaultValue("")]
    public int? Bar2;
}

you can't set a nullable int to default val of "" 你不能将一个nullable int设置为默认值""

Try 尝试

[DefaultValue(0)]
public int? Bar2;

Like @Dave A noticed you can not assign string value to the int value. 像@Dave A注意到你不能将字符串值赋给int值。

However one thing that I wanted to warn it, have you set properly the property DefaultValueHandling ? 但是有一件事我想警告它,你有没有正确设置DefaultValueHandling属性? Check it here: Removing Default Values in JSON with the MVC4 Web API 在此处查看: 使用MVC4 Web API删除JSON中的默认值

Besides that I would recommend to you that you do a string property that represent this Bar2 int property and you "Ignore" it for serialization, like: 除此之外,我建议您使用表示此Bar2 int属性的字符串属性,并“忽略”它以进行序列化,例如:

[JsonIgnore]
[DefaultValue(0)]
public int? Bar2Int;

public string Bar2
{
   return { Bar2Int.HasValue ? this.Bar2Int.Value.ToString() : String.Empty; }
}

Even better with this approach you do not need any default values attributes. 使用此方法更好,您不需要任何默认值属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM