How to convert dynamic JSON string into C# class?


Hello, I am not able to convert dynamic JSON response string into C# class object, it's a long JSON and i even tried to convert JSON into class using the  website http://json2csharp.com/ but it's doesn't provide me proper JSON class, Here is my sample JSON

 {
 	TITLE: "Voice (SIP/LD/Local/VoIP/POTS)",
 	SERVICES: {
 		33: {
 			TITLE: "Local T1",
 			DESCRIPTION: "Local Voice - T1",
 			QUESTIONS: [{
 				ID: 18,
 				TITLE: "How many minutes per month do you need?",
 				ANSWERS: [{
 						ID: 31,
 						TITLE: "Select one",
 						ISDEFAULTSELECTION: 1
 					},
 					{
 						ID: 32,
 						TITLE: "Under 10,000",
 						ISDEFAULTSELECTION: 0
 					},
 					{
 						ID: 33,
 						TITLE: "10,000 - 50,000",
 						ISDEFAULTSELECTION: 0
 					},
 					{
 						ID: 34,
 						TITLE: "50,000 - 100,000",
 						ISDEFAULTSELECTION: 0
 					},
 					{
 						ID: 35,
 						TITLE: "More than 100,000",
 						ISDEFAULTSELECTION: 0
 					}
 				],
 				ISREQUIRED: 1,
 				TYPE: "select list",
 				VALIDATIONTYPE: "selected"
 			}],
 			INSTALLATIONPHONEREQUIRED: 1
 		},
 	
 	},
 	DEFAULTSERVICEID: 83
 },

As in the above example, you can see , ID can be changed so I need dynamic JSON

I have checked this link https://qawithexperts.com/questions/7/how-to-convert-json-string-into-c-class-object

But I need dynamic solution, any help is appreciated, thanks


Asked by:- Vinnu
0
: 10198 At:- 2/23/2018 3:23:07 PM
JSON C# dynamic JSON to C# class json string into C# class







3 Answers
profileImage Answered by:- jaya

Using JSON.NET you can

dynamic details= JsonConvert.DeserializeObject("{ 'Name': 'Jaya', 'Address': { 'City': 'New Delhi', 'State': 'Delhi' }, 'Age': 31}");

string name = details.Name; //GET Name
string address = details.Address.City; //Get City

OR using using Newtonsoft.Json.Linq :

dynamic details= JObject.Parse("{ 'Name': 'Jaya', 'Address': { 'City': 'New Delhi', 'State': 'Delhi' }, 'Age': 31}");

string name = details.Name; //GET Name
string address = details.Address.City; //Get City

OR Using System.Web.Helpers.Json

var dynamicObject = Json.Decode(jsonString);

OR .Net 4.0 has a built-in library

using System.Web.Script.Serialization;
JavaScriptSerializer jss = new JavaScriptSerializer();
var d=jss.Deserialize<dynamic>(str);

OR using Newtonsoft.Json

using Newtonsoft.Json;

var result = JsonConvert.DeserializeObject<T>(json);
3
At:- 2/26/2018 6:51:05 AM Updated at:- 2/26/2018 6:51:35 AM
Thanks, I am using first approach of your answer 0
By : Vinnu - at :- 2/27/2018 12:29:42 PM


profileImage Answered by:- vikas_jk

You can also use JValue to parse JSON

    var jsonString = @"{""Name"":""TestName"",""Company"":""QA With Experts"",
                        ""Entered"":""2018-03-12T00:03:33.245-10:00""}";

    dynamic json = JValue.Parse(jsonString);

    // values require casting
    string name = json.Name;
    string company = json.Company;
    DateTime entered = json.Entered;

You must have Newtonsoft.Json installed, you can install it using Nuget command

PM> Install-Package Newtonsoft.Json

For Complex JSON string you can take a look a below example

 var jsonString = @"[
{
""Id"": ""b3ec4e5c"",
""AlbumName"": ""Dirty Deeds Done Dirt Cheap"",
""Artist"": ""AC/DC"",
""YearReleased"": 1976,
""Entered"": ""2012-03-16T00:13:12.2810521-10:00"",
""AlbumImageUrl"": ""http://ecx.images-amazon.com/images/I/61kTaH-uZBL._AA115_.jpg"",
""AmazonUrl"": ""http://www.amazon.com/gp/product/…ASIN=B00008BXJ4"",
""Songs"": [
    {
    ""AlbumId"": ""b3ec4e5c"",
    ""SongName"": ""Dirty Deeds Done Dirt Cheap"",
    ""SongLength"": ""4:11""
    },
    {
    ""AlbumId"": ""b3ec4e5c"",
    ""SongName"": ""Love at First Feel"",
    ""SongLength"": ""3:10""
    },
    {
    ""AlbumId"": ""b3ec4e5c"",
    ""SongName"": ""Big Balls"",
    ""SongLength"": ""2:38""
    }
]
},
{
""Id"": ""7b919432"",
""AlbumName"": ""End of the Silence"",
""Artist"": ""Henry Rollins Band"",
""YearReleased"": 1992,
""Entered"": ""2012-03-16T00:13:12.2800521-10:00"",
""AlbumImageUrl"": ""http://ecx.images-amazon.com/images/I/51FO3rb1tuL._SL160_AA160_.jpg"",
""AmazonUrl"": ""http://www.amazon.com/End-Silence-Rollins-Band/dp/B0000040OX/ref=sr_1_5?ie=UTF8&qid=1302232195&sr=8-5"",
""Songs"": [
    {
    ""AlbumId"": ""7b919432"",
    ""SongName"": ""Low Self Opinion"",
    ""SongLength"": ""5:24""
    },
    {
    ""AlbumId"": ""7b919432"",
    ""SongName"": ""Grip"",
    ""SongLength"": ""4:51""
    }
]
}
]";

    JArray jsonVal = JArray.Parse(jsonString) as JArray;
    dynamic albums = jsonVal;

    foreach (dynamic album in albums)
    {
        Console.WriteLine(album.AlbumName + " (" + album.YearReleased.ToString() + ")");
        foreach (dynamic song in album.Songs)
        {
            Console.WriteLine("\t" + song.SongName);
        }
    }

    Console.WriteLine(albums[0].AlbumName);
    Console.WriteLine(albums[0].Songs[1].SongName);
2
At:- 3/12/2018 7:23:41 AM


profileImage Answered by:- manish

Install JSON.NET using Nuget Package manager and use the below code to convert JSON into C#

var obj = Newtonsoft.Json.JsonConvert.DeserializeObject<ClassName>(jsonString);

also, if someone stumbles upon this want detailed implementation on How to read JSON data in C# please read the linked article, which I have written and will provide you working code sample using ASP.NET MVC and Console application.

OR you can also JSON to C# class online generator for quick coversions.

1
At:- 7/24/2018 4:22:49 PM Updated at:- 7/24/2018 4:23:28 PM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use