Click here to Skip to main content
14,878,669 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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);  
} 
Posted
Updated 9-Aug-17 11:16am

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.
   
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:
JavaScript
{'ID': '1','Name': 'Manas','Address': 'India',"data":{"EmpDeptId":"20172807"}}

Outputs:
XML
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; }
   }
   
v2
Comments
Richard Deeming 10-Aug-17 10:40am
   
If you're using VS2013 or later (or VS2012 with WebTools 2012.2 installed), and you have a reference to JSON.NET, there's no need for a service. :)
‘Paste JSON As Classes’ in ASP.NET and Web Tools 2012.2 RC[^]
Graeme_Grant 10-Aug-17 16:00pm
   
Yes, I am very aware of this but is not as flexible as the service plus has issues if there the JSON format is not simple. Hence my recommendation.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900