Click here to Skip to main content
14,838,044 members
Please Sign up or sign in to vote.
3.67/5 (2 votes)
See more:
Hi Friends,

i have a JSON string. I need to convert it into list of objects. How can i do this?
I created a class for this.Below are the details. please help
C#
string Restresponse = string.Empty;
Restresponse = reader.ReadToEnd();
JObject json = JObject.Parse(Restresponse);


C#
class Plans
   {
       public string AssumptionsOverrides { get; set; }
       public string ChannelId { get; set; }
       public string Clients { get; set; }
       public string CreatedDate { get; set; }
       public string CustomAssetClasses { get; set; }
       public string FaNumber { get; set; }
       public string Href { get; set; }
       public string LastAnalysisDate { get; set; }
       public string Name { get; set; }
       public string OfficeNumber { get; set; }
       public string PlanId { get; set; }
       public string Scenarios { get; set; }
       public string Settings { get; set; }
       public string UpdatedDate { get; set; }
       public string VerificationTimestamp { get; set; }

   }


JavaScript
{
	"plans": [{
		"planId": 10001,
		"name": "My Client Plan 1",
		"href": null,
		"channelId": "WSGPLN",
		"officeNumber": 101,
		"faNumber": 195,
		"createdDate": "2016-01-27T15:43:50",
		"updatedDate": "2016-01-27T15:43:50",
		"lastAnalysisDate": null,
		"clients": null,
		"scenarios": null,
		"settings": null,
		"assumptionsOverrides": null,
		"customAssetClasses": null,
		"verificationTimestamp": "2016-01-27T15:43:50"
	},
{
		"planId": 10025,
		"name": "My Client Plan 25",
		"href": null,
		"channelId": "WSGPLN",
		"officeNumber": 101,
		"faNumber": 195,
		"createdDate": "2016-01-27T15:43:50",
		"updatedDate": "2016-01-27T15:43:50",
		"lastAnalysisDate": null,
		"clients": null,
		"scenarios": null,
		"settings": null,
		"assumptionsOverrides": null,
		"customAssetClasses": null,
		"verificationTimestamp": "2016-01-27T15:43:50"
	}],
	"metadata": {
		"totalCount": 25,
		"offset": null,
		"limit": null
	}
}
Posted
Updated 6-Aug-18 19:31pm
Comments
BillWoodruff 28-Jan-16 4:38am
   
You need to de-serialize the JSON into an instance of your class object.

Do you have access to the code from which the JSON was serialized so you can examine the structure of the source class ?
jinesh sam 28-Jan-16 5:11am
   
I tried to de-serialize using the code below
List<Plans> P = JsonConvert.DeserializeObject<List>(Restresponse);
but its showing error. please help

The JSON you have doesn't match the class you are trying to deserialise to. Your JSON is a property called "plans" that is an array of objects that have a property called planId etc. The class you are deserialising to is an object that has a property called PlanID etc. When you deserialise that JSON into that class it will look to put the collection into an array\list property called plans but your Plan class has no such property.

You're going to have to either change the JSON or change your classes. This code uses the System.Runtime.Serialization classes, which will also need you to add some attributes to your classes, not just to allow them to be serialised, but also to take care of the fact that the case of property in your JSON doesn't match that on your class (I've done this on PlanID and Name to give you an example and to test it works, you'd need to do the others yourself). If you use a library like the Newtonsoft one already mentioned I dare say you won't have these fiddly issues, you'll be able to use your classes without bothering about special annotations, I'm only using this method as it works out of the box.

The updated classes

C#
[DataContract]
class Plans
{
    [DataMember]
    public List<Plan> plans { get; set; }
}

[DataContract]
class Plan
{
    [DataMember]
    public string AssumptionsOverrides { get; set; }
    [DataMember]
    public string ChannelId { get; set; }
    [DataMember]
    public string Clients { get; set; }
    [DataMember]
    public string CreatedDate { get; set; }
    [DataMember]
    public string CustomAssetClasses { get; set; }
    [DataMember]
    public string FaNumber { get; set; }
    [DataMember]
    public string Href { get; set; }
    [DataMember]
    public string LastAnalysisDate { get; set; }
    [DataMember(Name="name")]
    public string Name { get; set; }
    [DataMember]
    public string OfficeNumber { get; set; }
    [DataMember(Name="planId")]
    public string PlanId { get; set; }
    [DataMember]
    public string Scenarios { get; set; }
    [DataMember]
    public string Settings { get; set; }
    [DataMember]
    public string UpdatedDate { get; set; }
    [DataMember]
    public string VerificationTimestamp { get; set; }

}


Usage

C#
string json = "{\"plans\": [{.... ";

MemoryStream ms = new MemoryStream(System.Text.ASCIIEncoding.ASCII.GetBytes(json));
ms.Position = 0;

// Needs a reference to "System.Runtime.Serialization"
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Plans));
Plans p = (Plans) ser.ReadObject(ms);
   
v2
Comments
ridoy 28-Jan-16 14:56pm
   
nice, a 5.
Probably the best library to handle JSON in .NET...
Json.NET - Newtonsoft[^]
   
Comments
jinesh sam 28-Jan-16 3:49am
   
Thanks :)
you means something like this.
List<Plans> P = JsonConvert.DeserializeObject<List<plans>>(Restresponse);
I am getting error. can you please help
jinesh sam 28-Jan-16 3:50am
   
Error:
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[CallingAService.Plans]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
you can try this way

C#
public class Plan
{
    public int planId { get; set; }
    public string name { get; set; }
    public object href { get; set; }
    public string channelId { get; set; }
    public int officeNumber { get; set; }
    public int faNumber { get; set; }
    public string createdDate { get; set; }
    public string updatedDate { get; set; }
    public object lastAnalysisDate { get; set; }
    public object clients { get; set; }
    public object scenarios { get; set; }
    public object settings { get; set; }
    public object assumptionsOverrides { get; set; }
    public object customAssetClasses { get; set; }
    public string verificationTimestamp { get; set; }
}

public class Metadata
{
    public int totalCount { get; set; }
    public object offset { get; set; }
    public object limit { get; set; }
}

public class RootObject
{
    public List<Plan> plans { get; set; }
    public Metadata metadata { get; set; }
}
//c# convert to objects
 string json = "your jsonstring";
            
            RootObject rootObject = new JavaScriptSerializer().Deserialize<rootobject>(json);

</rootobject>
   
v2
Comments
jinesh sam 29-Jan-16 1:26am
   
Thanks Anil:) System.Web.Extension reference has to be added and System.Web.Script.Serialization namespace

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