gpt4 book ai didi

c# - 读取 JSON 文件并映射到 C# 对象

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

我想读取一个 JSON 文件并将其映射到类对象。我将如何在 C# 中执行此操作?

JSON

{  
"companyName":"Test company",
"companyNumber":"1234",
"address":{
"buildingNumber":"33",
"street":"Caledon Road",
"county":"Barking and Dagenham",
"postalTown":"Essex",
"postcode":"E62HE"
}
}

C#代码

public class CompanyInfo
{
public string companyName{ get;set;}
public string companyNumber{ get;set;}
public string buildingNumber{ get;set;}
public string street{ get;set;}
public string county{ get;set;}
public string postalTown{ get;set;}
public string postCode{ get;set;}
}

最佳答案

编写代码

    var json = {  
"companyName":"Test company",
"companyNumber":"1234",
"address":{
"buildingNumber":"33",
"street":"Caledon Road",
"county":"Barking and Dagenham",
"postalTown":"Essex",
"postcode":"E62HE"
}
}

public class CompanyInfo
{
public string companyName{ get;set;}
public string companyNumber{ get;set;}
public Address address {get;set;}
}

public class Address
{
public string buildingNumber{ get;set;}
public string street{ get;set;}
public string county{ get;set;}
public string postalTown{ get;set;}
public string postCode{ get;set;}
}

然后使用Newtonsoft.Json反序列化json

var results = JsonConvert.DeserializeObject<CompanyInfo>(json);

关于c# - 读取 JSON 文件并映射到 C# 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37206504/

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