【发布时间】:2019-09-12 12:15:36
【问题描述】:
我有一个有四个属性的类,最后两个可能为空。如果是,我不想在结果集中返回它们。
public class Foo
{
public string prop1 { get; set; }
public string prop2 { get; set; }
public string prop3 { get; set; }
public string prop4 { get; set; }
}
还有这个 Azure 函数:
[FunctionName("Func1")]
public Task<IActionResult> GetFunc1([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req)
{
Foo foo = new foo();
foo.prop1 = "string1";
foo.prop2 = "string2"; // prop3 and 4 are undefined
var result = foo.GetType().GetProperties()
.Where(x => x.PropertyType == typeof(string)) // check type
.Select(x => (x.Name + ": " + (string)x.GetValue(foo))) // get values
.Where(value => !string.IsNullOrEmpty(value)); // filter results
return Task.FromResult<IActionResult>(new JsonResult(result)
{
StatusCode = 200
});
}
返回
{
"prop1: string1",
"prop2: string2",
"prop3: ",
"prop4: "
}
它不是 json 格式(每个属性和值都应该用双引号括起来。空属性也会被返回,但不应该如此。如果我将结果计算修改为:
var result = foo.GetType().GetProperties()
.Where(x => x.PropertyType == typeof(string)) // check type
.Select(x => (string) x.GetValue(foo)) // get values
.Where(value => !string.IsNullOrEmpty(value) // filter result
我只得到没有像
这样的属性名称的值{
"string1",
"string2"
}
如何格式化结果查询以返回 json 格式的非空属性和值,如下所示:
{
"prop1": "string1",
"prop2": "string2"
}
编辑:这是@Matt 和@rené-carannanante 在重复问题中提出的解决方案:
首先,用属性更新类:
public class Foo
{
public string prop1 { get; set; }
public string prop2 { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string prop3 { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string prop4 { get; set; }
}
其次,通过让 Newtonsoft.Json 为我们自动删除空属性的工作来清理我的函数:
[FunctionName("Func1")]
public Task<IActionResult> GetFunc1([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req)
{
Foo foo = new foo();
foo.prop1 = "string1";
foo.prop2 = "string2"; // prop3 and 4 are undefined
return Task.FromResult<IActionResult>(new JsonResult(foo)
{
StatusCode = 200
});
}
它现在会自动返回正确的 json:
{
"prop1": "string1",
"prop2": "string2"
}
而不是没有 nullValueHandling 的默认值:
{
"prop1": "string1",
"prop2": "string2",
"prop3": null,
"prop4": null
}
【问题讨论】:
-
如果在选择之前有这样的 where 怎么办: .Where(x => (x.PropertyType == typeof(string)) && !string.IsNullOrEmpty(x.GetValue(foo)) ) ?
-
是的,谢谢@Matt 和 René - 我想我隐约记得 NullValueHandling=NullValueHandling.Ignore 属性,但没想到在这里应用它。这可以完美地自动删除空值。再次感谢您的专业知识!我会支持你的 cmets,但没有足够的声誉/积分来做到这一点......
-
我建议在这里发布您的解决方案并将其标记为答案,以便可以关闭问题并且其他人可以看到解决方案:)
-
@LajosArpad - 如果我使用该语法,它会抱怨您建议添加的代码的第二部分,并带有错误
Argument 1: cannot convert from 'object' to 'string'。 -
我明白了。我们可以解决这个问题,但没有必要这样做,因为问题已经解决了。
标签: c# rest azure-functions