[英]Read JSON file and map to C# objects
我想读取一个JSON文件并将其映射到类对象。 我将如何在C#中做到这一点?
{
"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 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);
首先创建一个与JSON相匹配的类,这可以使用此超级方便的工具json2csharp.com轻松完成
您提供的JSON会转换为此
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; }
}
public class RootObject
{
public string companyName { get; set; }
public string companyNumber { get; set; }
public Address address { get; set; }
}
然后将JSON反序列化为您刚刚使用JSON.net定义的类型的对象(nuget Install-Package Newtonsoft.Json)
public void LoadJson()
{
using (StreamReader r = new StreamReader("file.json"))
{
string json = r.ReadToEnd();
RootObject company = JsonConvert.DeserializeObject<RootObject>(json);
}
}
我建议将RootObject重命名为应用程序中更有意义的名称
您需要两个类CompanyInfo
和Address
。 CompanyInfo
必须包含Address
对象,因为json在companyInfo中具有address对象:
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
NuGet Package或其他方法反序列化json。
您必须使用JSON.Net 在此处输入链接描述
本文也可能很有趣: 如何使用C#解析JSON?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.