JSON反序列化:里面有多个对象 [英] JSON deserialization : multiple object inside

查看:148
本文介绍了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.


一种简单的方法是使用可以将JSON转换为C#类的服务。我最喜欢的是: JSON Utils:从JSON生成C#,VB.Net,SQL表,Java和PHP [ ^ ]



使用:

An easy way is to use a service that can convert JSON into C# classes. My favourite is: JSON Utils: Generate C#, VB.Net, SQL Table, Java and PHP from JSON[^]

Using:
{'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反序列化:里面有多个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆