JObject 检查是否只有特定属性具有有效值

问题描述 投票:0回答:1

我有这样的 json 响应字符串

{
"last_name":"",
"first_name":"",
"SSN":"Particular value",
"passport_data":[],
"e_civil":"",
"vehicle_info":"",
"driving_license":"",
"e_register":"",
"ces_data":""
}

我正在将此字符串解析为 JObject

    var jObj = (JObject)JsonConvert.DeserializeObject(response);

现在我想检查所有属性是否为 null 或空字符串,如果只有 SSN 具有有效值(不是 null 或空字符串),则返回错误。

c# asp.net json asp.net-web-api2
1个回答
0
投票

这是您可以使用的代码 - 只需将

JObject
的索引器与您要访问的属性名称一起使用:

var json = @"{
    ""last_name"":"""",
    ""first_name"":"""",
    ""SSN"":""Particular value"",
    ""passport_data"":[],
    ""e_civil"":"""",
    ""vehicle_info"":"""",
    ""driving_license"":"""",
    ""e_register"":"""",
    ""ces_data"":""""
}";
// You can deserialize directly to JObject.
var o = JsonConvert.DeserializeObject<JObject>(json);
// Access the value of property.
Console.WriteLine(o["SSN"]);
© www.soinside.com 2019 - 2024. All rights reserved.