gpt4 book ai didi

c# - 将 JSON 加载到 C# 对象中

转载 作者:太空宇宙 更新时间:2023-11-03 12:41:53 24 4
gpt4 key购买 nike

我有一个 JSON 文件,我需要将其转换为 C# 对象,然后将其写入 SQL 数据库。 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"
}]
}
}

我有一个如下所示的 C# 类:

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

public class Locations
{
public List<Location> Location { get; set; }
}

我正在使用 Newtonsoft JSON 库。当外部值“AK”、“Anchorage”、“Fairbanks”没有通用名称时,我不确定如何获取内部值(名称、地址、城市、州、 zip )?

最佳答案

使用 NewtonSoft :

Location location = JsonConvert.DeserializeObject<Location>(json);

你的类看起来像这样:

public class Location
{
public IList<Address> Addresses { get; set; }
}

public class Address {
public string AddressName { get; set; }
[JsonProperty("Name")] # You'll need attributes if the dataset has another name than that of the object's property.
public string PersonName { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
}

示例修改自 here .

快速更新,我重新阅读了这个问题,发现您也很难迭代对象。错过了第一轮,给你:

var locations = new List<Location>();
dynamic deserialisedJson = JsonConvert.DeserializeObject(json);

// E.g., json => List ( "AK": { ... }, ... )
// so we're iterating the items of that "list", e.g., "AK": { ... }, etc.
foreach (var state in deserialisedJson)
{
// e.g., "AK": { ... } => List ( Anchorage: [{ ... }], Fairbanks: [{ ... }] )
// so we're iterating the items of each item, e.g., Anchorage: [{ ... }], etc.
foreach (var addresses in state)
{
// e.g., Anchorage: [{ ... }, { ... }] => List ( { ... }, { ... } )
// because Anchorage, etc., are arrays, we have to iterate their contents too, to get each address object within them (represented as { ... } above:
foreach (var address in addresses) {
Location location = JsonConvert.DeserializeObject<Location>(address);
// do stuff with location, e.g.,
locations.Add(location);
}
}
}

关于c# - 将 JSON 加载到 C# 对象中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38699575/

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