Retrieving json data which in C#

2019-09-21 23:43发布

问题:

I want to deserialise the following Json. I have tried the following:

JSON Data:

{
  "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",
              }]
          }]
      }],
}

Code:

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();
}
}

回答1:

Create C# classes that map to your json. As below:

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; }
}

and then

WebClient c = new WebClient();
var json = c.DownloadString("sampleurl");
Data data = JsonConvert.DeserializeObject<Data>(json);