我想反序列化以下 Json。我尝试了以下方法:
JSON数据:
{
"data":[
{
"employee":[
{
"empdetails":[
{
"empid":"40",
"empname":"Amit",
"empdept":"Director",
"empphone":[
{
"home":"23432235",
"office":"2352353",
}]
},
{
"empid":"54",
"empname":"Abhishek",
"empdept":"HR",
"empphone":[
{
"home":"5445457",
"office":"34634634",
}]
},
{
"empid":"80",
"empname":"Rahul",
"empdept":"Finance"
},
{
"empid":"71",
"empname":"Anand",
"empdept":"Marketing",
"empphone":[
{
"home":"46346346",
"office":"346346346",
}]
}]
}],
}
法典:
using System;
using Newtonsoft.Json.linq;
using System.Collections.Generics;
class Program
{
public class emp
{
public int empid {get; set;}
public string empname {get; set;}
public string empdept {get; set;}
public string empcontact {get; set; }
}
static void main(string[] args)
{
WebClient c= new WebClient();
var json = c.DownloadString(new uri("sampleurl"));
dynamic dynamicObj=JsonConvert.DeserializeObject(json);
foreach (var data in dynamicObj.data)
{
foreach (var getempdet in data.employee)
{
foreach(var dat in getempdet)
{
foreach(var datas in dat)
{
foreach(var getempdetails in datas)
{
foreach(var finaldata in getempdetails)
{
Console.WriteLine("t{0}", finaldata);
List<emp> empList=newList<emp>();
}
}
}
}
}
}
Console.ReadLine();
}
}
创建映射到json
的 C# 类。如下:
public class Data
{
public List<Employee> Employees { get; set; }
}
public class Employee
{
public List<EmpDetails> EmpDetailss { get; set; }
}
public class EmpDetails
{
public int Empid { get; set; }
public string Empname { get; set; }
public string Empdept { get; set; }
public EmpPhone EmpPhone{ get; set; }
}
public class EmpPhone
{
public string Home { get; set; }
public string Office { get; set; }
}
然后
WebClient c = new WebClient();
var json = c.DownloadString("sampleurl");
Data data = JsonConvert.DeserializeObject<Data>(json);