Click here to Skip to main content
15,885,278 members
Articles / Programming Languages / C#

Get Required Property from Complex json string in C# with Newtonsoft

25 Dec 2015CPOL1 min read 19.7K   4   4
In this blog, I will tell you the trick to convert JSON string property to C# Object using Newtonsoft.

Introduction

In this blog, I will tell you the trick to convert JSON string property to C# Object using Newtonsoft.

Illustration

Suppose the JSON string is like…

JavaScript
{
  "Success": true,
  "ComplexObject": {
    "NormalProp": "Test",
    "ListOfAnotherClass": [{
      "JustAStringProp": "We"
    }, {
      "JustAStringProp": "Got"
    }, {
      "JustAStringProp": "Values"
    }]
  }
}

Now, if I get this string from some method and try to process, I would need to convert this to C# objects. The structure would look something like below. To easily get the class structure, you can use any online tool like json2csharp.

C#
class Result
{
	public bool Success { get; set; }
	public ComplextJsonClass ComplexObject { get; set; }
}

class ComplextJsonClass
{
	public string NormalProp { get; set; }
	public List<AnotherClass> ListOfAnotherClass { get; set; }
}

class AnotherClass
{
	public string JustAStringProp { get; set; }
}

What We Need?

So, for processing, I would like to get the “ComplexObject” property of this JSON string converted as “ComplextJsonClass” C# object. As the JSON string is complex with other property like “Success“, we only need the property “ComplexObject“, yet converted to a C# object.

How To Do That?

We will use Newtonsoft. You can easily find that from Nuget and add that as a reference to your project.

Solution

First of all, I will tell you how to generate this type of JSON.

C#
var complex = new ComplextJsonClass
{
	NormalProp = "Test",
	ListOfAnotherClass = new List<AnotherClass>
	{
		new AnotherClass{JustAStringProp = "We"},
		new AnotherClass{JustAStringProp = "Got"},
		new AnotherClass{JustAStringProp = "Values"},
	}
};

var moreComplex = new Result {Success = true, ComplexObject = complex};
var jsonString = JsonConvert.SerializeObject(moreComplex);

This “jsonString” comes as I mentioned in the beginning of the post. Now, we need to convert this JSON to a C# Object. For this, we need to use JsonConvert.DeserializeObject Method (String).

C#
var jsonObject = JsonConvert.DeserializeObject(jsonString);

But, unfortunately, this alone won’t help us more to access the properties. We have to convert to a JObject, by which we can easily access the properties from the JSON.

C#
var jsonObject = (JObject)JsonConvert.DeserializeObject(jsonString);

After this, it is just a matter of getting the property by using jsonObject["ComplexObject"].

C#
var jsonObject = (JObject)JsonConvert.DeserializeObject(jsonString);
if (jsonObject["ComplexObject"] == null) return;

ComplextJsonClass complexObject = JsonConvert.DeserializeObject<ComplextJsonClass>
            (jsonObject["ComplexObject"].ToString());

Convert to C# Object from Newtonsoft JObject

Convert to C# Object from Newtonsoft JObject

Full Code

C#
var complex = new ComplextJsonClass
{
	NormalProp = "Test",
	ListOfAnotherClass = new List<AnotherClass>
	{
		new AnotherClass{JustAStringProp = "We"},
		new AnotherClass{JustAStringProp = "Got"},
		new AnotherClass{JustAStringProp = "Values"},
	}
};

// Get the jsonString from complex object.
var moreComplex = new Result {Success = true, ComplexObject = complex};
var jsonString = JsonConvert.SerializeObject(moreComplex);

//Now let's deserialize and convert to our required ComplextJsonClass object.
var jsonObject = (JObject)JsonConvert.DeserializeObject(jsonString);
if (jsonObject["ComplexObject"] == null) return;

ComplextJsonClass complexObject = JsonConvert.DeserializeObject<ComplextJsonClass>
            (jsonObject["ComplexObject"].ToString());

Feedback

Let me know if this trick helped you in any way in your projects or assignments. Re-post or share, if you liked it.

Thanks a lot for reading. Marry Christmas and Happy New Year. :)

License

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


Proud Indian | Author | TEDx Speaker | Microsoft MVP | CodeProject MVP | Speaker | DZone Most Valuable Blogger| jsfiddler

My Website

taditdash.com

Programming Community Profiles

jsfiddle | Stack Overflow

Social Profiles

Facebook | Twitter | LinkedIn

Awards


  1. DZone Most Valuable Blogger
  2. Microsoft MVP 2014, 2015, 2016, 2017, 2018
  3. Code Project MVP 2014, 2015, 2016
  4. Star Achiever of the Month December 2013
  5. Mindfire Techno Idea Contest 2013 Winner
  6. Star of the Month July 2013

Comments and Discussions

 
QuestionIsn't this just overhead? Pin
Member 120748333-Jan-16 17:59
Member 120748333-Jan-16 17:59 
AnswerRe: Isn't this just overhead? Pin
Tadit Dash (ତଡିତ୍ କୁମାର ଦାଶ)3-Jan-16 18:07
protectorTadit Dash (ତଡିତ୍ କୁମାର ଦାଶ)3-Jan-16 18:07 
GeneralRe: Isn't this just overhead? Pin
Member 120748333-Jan-16 18:16
Member 120748333-Jan-16 18:16 
GeneralRe: Isn't this just overhead? Pin
Tadit Dash (ତଡିତ୍ କୁମାର ଦାଶ)3-Jan-16 21:01
protectorTadit Dash (ତଡିତ୍ କୁମାର ଦାଶ)3-Jan-16 21:01 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.