gpt4 book ai didi

c# - 识别一个属性的值是一个数组

转载 作者:太空狗 更新时间:2023-10-30 00:24:12 24 4
gpt4 key购买 nike

我有一个 JSON 文件:

{  
"abn":"63119059513",
"acn":"119059513",
"business_structure":"Private Company",
"ngr_number":"1231231",
"cbh_number":"1231231",
"main_name":"Brickworks Building Products Pty Ltd",
"trading_name":"Brickworks",
"other_trading_names":"Austral Bricks",
"directors":[
{
"ID":"12114",
"ae_forms_filled_in_ID":"22739",
"name":"John Smith",
"dob":"1983-10-29",
"address_line_1":"123 Fake Street",
"address_line_2":"",
"address_line_city":"Fakeland",
"address_line_postcode":"2000",
"address_line_state":"New South Wales",
"address_line_country":"Australia",
"order_extract_id":null,
"director_found":null,
"drivers_lic":"",
"home_mortgage":"",
"phone":"",
"mobile":"",
"director_email":"",
"director_title":"Mr",
"director_position":"Director",
"dir_pdf_url":null
}
],

}

我想确定任何属性的值是否具有数组结构。到目前为止我能想到的最好的是:

StreamReader streamrr = new StreamReader("C:\\temp\\agfarm_example_udate.json", Encoding.UTF8);

string JSON = streamrr.ReadToEnd();

JObject CWFile = JObject.Parse(JSON);
foreach (JProperty property in CWFile.Properties())
{
// Do something

if (property.Value.ToString().Contains("["))
{
// Do something with the array
JArray items = (JArray)CWFile[property.Name];

foreach (JObject o in items.Children<JObject>())
{
foreach (JProperty p in o.Properties())
{
// Do something
}
}
}
}

为了判断一个属性值是否有一个数组,我使用了条件:

if (property.Value.ToString().Contains("["))

我只是想知道是否有更好的方法来进行此检查?

最佳答案

执行此操作的一种方法是检查 JToken.Type 属性。数组的类型为 JTokenType.Array:

if (property.Value.Type == JTokenType.Array)
{
var items = (JArray)property.Value;

// Proceed as before.
}

或者,您可以尝试转换为 JArray:

if (property.Value is JArray)
{
var items = (JArray)property.Value;

// Proceed as before.
}

两者都比检查 property.Value.ToString().Contains("[") 更可取,因为嵌套属性可能有一个数组值,从而导致括号出现在 >ToString() 返回。

如果你想递归地找到每个具有数组值的属性,你可以引入一个扩展方法:

public static class JsonExtensions
{
public static IEnumerable<JToken> WalkTokens(this JToken node)
{
if (node == null)
yield break;
yield return node;
foreach (var child in node.Children())
foreach (var childNode in child.WalkTokens())
yield return childNode;
}
}

然后做:

var CWFile = JToken.Parse(JSON)
var arrayProperties = CWFile.WalkTokens().OfType<JProperty>().Where(prop => prop.Value.Type == JTokenType.Array);

关于c# - 识别一个属性的值是一个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28035964/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com