gpt4 book ai didi

c# - 从 IEnumerable foreach 循环中获取值

转载 作者:行者123 更新时间:2023-11-30 16:47:57 30 4
gpt4 key购买 nike

我需要从 JSON 文件创建一个 c# 对象,并且必须遵循以下工作解决方案:

JSON:

{
"AK": {
"Anchorage": [{
"Name": "John Doe",
"Address": "123 Main St.",
"City": "Anchorage",
"State": "AK",
"Zip": "12345"
}],
"Fairbanks": [{
"Name": "Sally Smith",
"Address": "987 Main St.",
"City": "Fairbanks",
"State": "AK",
"Zip": "98765"
}]
}
}

代码:

public class Location
{
public string Name { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
}

// ------------------------------------------------------------------
string json = File.ReadAllText(@"C:json.txt");
dynamic deserialisedJson = JsonConvert.DeserializeObject(json);

var locations = new List<Location>();

foreach (var root in deserialisedJson)
{
foreach (var state in root)
{
foreach (var city in state)
{
foreach (var location in city)
{
Location loc = new Location();
loc.Name = location.First["Name"];
loc.Address = location.First["Address"];
loc.City = location.First["City"];
loc.State = location.First["State"];
loc.Zip = location.First["Zip"];
locations.Add(loc);
}
}
}
}

但我需要将以上内容合并到一个 SSIS 包中,它只允许 .NET 3.5 及以下版本。下面的代码行需要 .NET 4.0 及更高版本:

dynamic deserialisedJson = JsonConvert.DeserializeObject(json);

我正在尝试通过使用 IEnumerable 来解决此限制,但我不确定如何获取我需要的值的语法?

string json = File.ReadAllText(@"C:json.txt");

var deserialisedJson = (IEnumerable)JsonConvert.DeserializeObject(json);

var locations = new List<Location>();

foreach (var root in deserialisedJson)
{
foreach (var state in (IEnumerable)root)
{
foreach (var city in (IEnumerable)state)
{
foreach (var location in (IEnumerable)city)
{
Location loc = new Location();

loc.Name = //What goes here???
loc.Address = //What goes here???
loc.City = //What goes here???
loc.State = //What goes here???
loc.Zip = //What goes here???

locations.Add(loc);
}
}
}
}

最佳答案

这使用 Linq to JSON选择您想要的所有 Location 对象:

var deserialisedJson = (IEnumerable)JsonConvert.DeserializeObject(json);
JObject jObj = JObject.Parse(json);

//Get all tokens that are under AK/(some descendant)/all items from collection
var result = jObj.SelectTokens("AK.*.[*]")
.Select(x => new Location
{
Name = x["Name"].Value<string>(),
Address = x["Address"].Value<string>(),
City = x["City"].Value<string>(),
State = x["State"].Value<string>(),
Zip = x["Zip"].Value<string>(),
}).ToList();

经过测试,这适用于 .Net 3.5 项目,带有适合 .Net 的 Newtonsoft.Json

关于c# - 从 IEnumerable foreach 循环中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38744667/

30 4 0