Skip to main content

Command Palette

Search for a command to run...

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

Updated
β€’3 min read
Get Required Property from Complex json string in C# with Newtonsoft
T

As a πŸš€ Vice President with over 12 years of experience, I am a seasoned software architect known for designing and leading teams of engineers to deliver high-quality software products promptly and within budget.

Throughout my career, I have spearheaded the end-to-end design of 7 innovative software products 🎯.

From conceptualization to deployment planning, I have successfully guided teams through requirements gathering, prototyping, testing, and deployment phases, ensuring exceptional outcomes.

I take pride in my industry recognition, including being honored as a πŸ’Ž Microsoft Most Valuable Professional, πŸ’‘ CodeProject Most Valuable Professional, and πŸ† DZone Most Valuable Blogger.

Additionally, my expertise has been acknowledged by BookAuthority, which recognized my books on ASP.NET, REST API, Vue.js, and Dependency Injection as the πŸ“š best of all time.

In addition to my professional achievements, I am passionate about mentorship and have been privileged to serve as a 🌟 Young Mentor at IndiaMentor, guiding aspiring professionals in their career journeys.

For further information about my work and insights, please visit my website at 🌐 http://taditdash.com.

You can also connect with me on 🐦 Twitter at https://twitter.com/taditdash, πŸ‘ Facebook at https://www.facebook.com/taditdash, and πŸ’Ό LinkedIn at https://www.linkedin.com/in/taditdash.

I am always open to networking and discussing opportunities, so feel free to reach out and connect.

Let's explore how we can collaborate and drive innovation in the ever-evolving world of software architecture and development.

Introduction

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

Illustration

Suppose the JSON string is like…

{
  "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.

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 properties 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, I will tell you how to generate this type of JSON.

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 at 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).

    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.

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

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

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

Full Code

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. Merry Christmas and Happy New Year. πŸ˜€πŸ€