c# - 我可以反序列化 JSON 中的特定字段吗?

标签 c# .net json json.net

我正在编写一个方法,该方法采用英国邮政编码并将此邮政编码的纬度和经度作为“位置”对象返回。

public class Location
{
    public double Longitude;
    public double Latitude;
}

我正在使用来自 https://postcodes.io/ 的 API它需要一个邮政编码并返回一个相当大的数据集。例如(白金汉宫,如果你感兴趣的话):

{
"status": 200,
"result": {
    "postcode": "SW1A 1AA",
    "quality": 1,
    "eastings": 529090,
    "northings": 179645,
    "country": "England",
    "nhs_ha": "London",
    "longitude": -0.141587597876975,
    "latitude": 51.5010091564599,
    "european_electoral_region": "London",
    "primary_care_trust": "Westminster",
    "region": "London",
    "lsoa": "Westminster 018C",
    "msoa": "Westminster 018",
    "incode": "1AA",
    "outcode": "SW1A",
    "parliamentary_constituency": "Cities of London and Westminster",
    "admin_district": "Westminster",
    "parish": "Westminster, unparished area",
    "admin_county": null,
    "admin_ward": "St James's",
    "ccg": "NHS Central London (Westminster)",
    "nuts": "Westminster",
    "codes": {
        "admin_district": "E09000033",
        "admin_county": "E99999999",
        "admin_ward": "E05000644",
        "parish": "E43000236",
        "parliamentary_constituency": "E14000639",
        "ccg": "E38000031",
        "nuts": "UKI32"
        }
    }
}

目前,我已将其设置为通过使用 Visual Studio 的“选择性粘贴 > 将 JSON 作为类粘贴”功能为数据生成类来获取数据,然后使用 JSON.Net 反序列化整个数据集,然后使用纬度和结果对象的经度以创建一个新的 Location 对象。

Rootobject locationData = JsonConvert.DeserializeObject<Rootobject>(content);

        Location locationToReturn = new Location()
        {
            Latitude = locationData.result.latitude,
            Longitude = locationData.result.longitude
        };

当我只想要两个字段时,我必须经历整个事情的反序列化,这对我来说似乎很愚蠢。

那么问题是:

我可以只反序列化纬度和经度字段吗?

更具体地针对我的示例,我可以将纬度和经度字段直接反序列化到我的 Location 类的新实例中吗?

最佳答案

您可以将数据加载到动态对象中。 然后从那里开始阅读。

        dynamic locationData = JsonConvert.DeserializeObject<dynamic>(content);

        Location locationToReturn = new Location()
        {
            Latitude = locationData.result.latitude,
            Longitude = locationData.result.longitude
        };

        Console.WriteLine("Latitude: " + locationToReturn.Latitude);
        Console.WriteLine("Longitude: " + locationToReturn.Longitude);

        Console.ReadLine();

通过这种方式,您也可以获得其他列或值,而无需枚举所有字段。

关于c# - 我可以反序列化 JSON 中的特定字段吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48304879/

相关文章:

c# - 如何打开服务属性对话框

C#过滤对象集合

c# - WPF 功能区 : Maximized window going off screen

c# - ASP.NET:在某些情况下我应该担心内存泄漏吗? [C#]

php - 嵌套 JSON 数组在 mySQL 表中是什么样子?

java - 从 Play Framework Controller 返回 JSON 字符串

c# - 没有名为 fcntl 的模块

c# - 如何在C#.NET中修改其他Form的RichTextBox

c# - 我应该在 NETPortable 中引用哪个,找不到 GetMethods

java - 如何使用 JSON 负载对 Dynamo DB 表执行 updateItem 操作