How to use JObject in C#

JObject Class represents a JSON object. It helps to parse JSON data and apply querying (LINQ) to filter out required data.


Newtonsoft.Json.Linq.JObject


The JSON string represents an object with two properties which is parsed into a JObject class and cast to dynamic.


Creating JSON with JObject


JArray represents a JSON Array. We can add elements to JArray object and convert into JSON string.


Usage :


using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.Linq;

namespace JObjectApp
{
    class Program
    {
        static void Main(string[] args)
        {

            string json = "{Users:[{\"UserName\":\"cihanasan\", \"Password\":\"12345\"}, {\"UserName\":\"mikeanderson\", \"Password\":\"mike123\"}, {\"UserName\":\"tomwasson\", \"Password\":\"wasson1234\"}]}";


            dynamic temp = Newtonsoft.Json.Linq.JObject.Parse(json);

            JArray users = temp.Users;

            IList<string> user = users.Select(x => x.ToString()).ToList();
        }

    }
}

The simplest way to get a value from LINQ to JSON is to use the index methods on JObject/JArray as shown below


JObject_1.png

Getting values by Property Name

Usage of JObject Parse :


json = "{\"FirstName\":\"Cihan\", \"LastName\":\"ASAN\"}"
var temp = Newtonsoft.Json.Linq.JObject.Parse(json)
temp.FirstName, temp.LastName

tag : JObject System.ArgumentException: 'Can not convert Object to String.'