本文介绍了JSON反序列化:里面有多个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I have sample code ,that work fine.

public class Employee  
{  
    public int ID { get; set; }  
    public string Name { get; set; }  
    public string Address { get; set; }  
}  


   private void JSONDeserilaize()  
{  
    string json = @"{  
        'ID': '1',  
        'Name': 'Manas',  
        'Address': 'India'  
    }";  

    Employee empObj = JsonConvert.DeserializeObject<Employee>(json);  

    Response.Write(empObj.Name);  
}  

But my json string is in this format.

string json = @"{'ID': '1','Name': 'Manas','Address': 'India',"data":{"EmpDeptId":"20172807"}}";

How to fetch EmpDeptId along with Id,Name and Address.





我尝试过的:





What I have tried:

public class Employee  
{  
    public int ID { get; set; }  
    public string Name { get; set; }  
    public string Address { get; set; }  
}  
 

   private void JSONDeserilaize()  
{  
    string json = @"{  
        'ID': '1',  
        'Name': 'Manas',  
        'Address': 'India'  
    }";  
 
    Employee empObj = JsonConvert.DeserializeObject<Employee>(json);  
 
    Response.Write(empObj.Name);  
} 

推荐答案

public class EmployeeData
{
    public int EmpDeptId { get; set; }
}

public class Employee  
{  
    public int ID { get; set; }  
    public string Name { get; set; }  
    public string Address { get; set; }  
    public EmployeeData Data { get; set; }
}  





未经测试,但如上所述,您创建的数据属性属于支持数据结构。



Untested, but something like the above, you create a "Data" property that is of a type that supports the data structure.


{'ID': '1','Name': 'Manas','Address': 'India',"data":{"EmpDeptId":"20172807"}}



输出:


Outputs:

public class Data
   {

       [JsonProperty("EmpDeptId")]
       public string EmpDeptId { get; set; }
   }

   public class Employees
   {

       [JsonProperty("ID")]
       public string ID { get; set; }

       [JsonProperty("Name")]
       public string Name { get; set; }

       [JsonProperty("Address")]
       public string Address { get; set; }

       [JsonProperty("data")]
       public Data Data { get; set; }
   }


这篇关于JSON反序列化:里面有多个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 16:02