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

标签 c# json

我有一个 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/

相关文章:

c# - 在不添加 WebReference 的情况下调用 Webservice - 具有复杂类型

c# - 如何将 PresentationFramework.Aero 主题添加到 ResourceDictionary

c# - 如何在Javascript中处理ObjectId,无法解析它

c# - 修改新集合而不触及原始集合

c# - 在没有 COM 的 Linux 上通过 PHP 运行 .NET DLL

python - 过滤超过 2.5GB Json 文件的最快方法是什么?

Javascript indexof 不适用于 json

json - 如何正确合并两个 ipython 笔记本而不会出现 json 错误?

c# - 为什么我在 Web 客户端中得到结果,即使服务器已关闭?

python - 来自curl的JSON作为函数参数