繁体   English   中英

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

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

我有一个返回json结果的动作,但有些属性为null,我想将它们转换为空字符串。 我听说我可以使用DefaultValue("") ,但它仍然返回null而不是空字符串。

行动是:

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

Foo类是:

public class Foo
{
    public string Bar1;

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

你不能将一个nullable int设置为默认值""

尝试

[DefaultValue(0)]
public int? Bar2;

像@Dave A注意到你不能将字符串值赋给int值。

但是有一件事我想警告它,你有没有正确设置DefaultValueHandling属性? 在此处查看: 使用MVC4 Web API删除JSON中的默认值

除此之外,我建议您使用表示此Bar2 int属性的字符串属性,并“忽略”它以进行序列化,例如:

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

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

使用此方法更好,您不需要任何默认值属性。

暂无
暂无

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

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