Creating JSON on the fly with JObject

create dynamic json object c#
create json object c#
create jobject from object c#
.net core build json object
add item to json object c#
could not determine json object type for type
jtoken to jobject
.net core dynamic object to json

For some of my unit tests I want the ability to build up particular JSON values (record albums in this case) that can be used as input for the system under test.

I have the following code:

var jsonObject = new JObject();
jsonObject.Add("Date", DateTime.Now);
jsonObject.Add("Album", "Me Against The World");
jsonObject.Add("Year", 1995);
jsonObject.Add("Artist", "2Pac");

This works fine, but I have never really like the "magic string" syntax and would prefer something closer to the expando-property syntax in JavaScript like this:

jsonObject.Date = DateTime.Now;
jsonObject.Album = "Me Against The World";
jsonObject.Year = 1995;
jsonObject.Artist = "2Pac";

Well, how about:

dynamic jsonObject = new JObject();
jsonObject.Date = DateTime.Now;
jsonObject.Album = "Me Against the world";
jsonObject.Year = 1995;
jsonObject.Artist = "2Pac";

Creating JSON, As well as parsing JSON from existing JSON strings, LINQ to JSON objects can Manually Creating JSON; Creating JSON with LINQ; Creating JSON from an object Internally, FromObject will use the JsonSerializer to serialize the object to  Creating JSON on the fly with JObject and JArray Let's start with creating some JSON on the fly. It's super easy to create a dynamic object structure with any of the JToken derived JSON.NET objects. The most common JToken derived classes you are likely to use are JObject and JArray.

You can use the JObject.Parse operation and simply supply single quote delimited JSON text.

JObject  o = JObject.Parse(@"{
  'CPU': 'Intel',
  'Drives': [
    'DVD read/writer',
    '500 gigabyte hard drive'
  ]
}");

This has the nice benefit of actually being JSON and so it reads as JSON.

Or you have test data that is dynamic you can use JObject.FromObject operation and supply a inline object.

JObject o = JObject.FromObject(new
{
    channel = new
    {
        title = "James Newton-King",
        link = "http://james.newtonking.com",
        description = "James Newton-King's blog.",
        item =
            from p in posts
            orderby p.Title
            select new
            {
                title = p.Title,
                description = p.Description,
                link = p.Link,
                category = p.Categories
            }
    }
});

Json.net documentation for serialization

Create JSON with dynamic, This sample creates T:Newtonsoft.Json.Linq.JObject and T:Newtonsoft.Json.Linq.​JArray instances using the C# dynamic functionality. Creating JSON on the fly with JObject and JArray Let's start with creating some JSON on the fly. It's super easy to create a dynamic object structure with any of the JToken derived JSON.NET objects. The most common JToken derived classes you are likely to use are JObject and JArray.

Neither dynamic, nor JObject.FromObject solution works when you have JSON properties that are not valid C# variable names e.g. "@odata.etag". I prefer the indexer initializer syntax in my test cases:

JObject jsonObject = new JObject
{
    ["Date"] = DateTime.Now,
    ["Album"] = "Me Against The World",
    ["Year"] = 1995,
    ["Artist"] = "2Pac"
};

Having separate set of enclosing symbols for initializing JObject and for adding properties to it makes the index initializers more readable than classic object initializers, especially in case of compound JSON objects as below:

JObject jsonObject = new JObject
{
    ["Date"] = DateTime.Now,
    ["Album"] = "Me Against The World",
    ["Year"] = 1995,
    ["Artist"] = new JObject
    {
        ["Name"] = "2Pac",
        ["Age"] = 28
    }
};

With object initializer syntax, the above initialization would be:

JObject jsonObject = new JObject
{
    { "Date", DateTime.Now },
    { "Album", "Me Against The World" },
    { "Year", 1995 }, 
    { "Artist", new JObject
        {
            { "Name", "2Pac" },
            { "Age", 28 }
        }
    }
};

Create JSON manually, This sample creates T:Newtonsoft.Json.Linq.JObject and T:Newtonsoft.Json.Linq.​JArray instances one at a time programatically. This sample creates T:Newtonsoft.Json.Linq.JObject and T:Newtonsoft.Json.Linq.JArray instances using the C# dynamic functionality.

There are some environment where you cannot use dynamic (e.g. Xamarin.iOS) or cases in where you just look for an alternative to the previous valid answers.

In these cases you can do:

using Newtonsoft.Json.Linq;

JObject jsonObject =
     new JObject(
             new JProperty("Date", DateTime.Now),
             new JProperty("Album", "Me Against The World"),
             new JProperty("Year", "James 2Pac-King's blog."),
             new JProperty("Artist", "2Pac")
         )

More documentation here: http://www.newtonsoft.com/json/help/html/CreatingLINQtoJSON.htm

Modifying JSON, This sample loads JSON, modifies T:Newtonsoft.Json.Linq.JObject and T:​Newtonsoft.Json.Linq.JArray instances and then writes the JSON back out again. Create a Student JSON with the following keys: Name, Class, Subjects, and Roll No. The name is a string, Class and Roll No. will be integer and Subject will be an Array. Pass the appropriate values to each key.

Simple way of creating newtonsoft JObject from Properties.

This is a Sample User Properties

public class User
{
    public string Name;
    public string MobileNo;
    public string Address;
}

and i want this property in newtonsoft JObject is:

JObject obj = JObject.FromObject(new User()
{
    Name = "Manjunath",
    MobileNo = "9876543210",
    Address = "Mumbai, Maharashtra, India",
});

Output will be like this:

{"Name":"Manjunath","MobileNo":"9876543210","Address":"Mumbai, Maharashtra, India"}

Using JSON.NET for dynamic JSON parsing, Let's start with creating some JSON on the fly. It's super easy to create a dynamic object  This sample creates T:Newtonsoft.Json.Linq.JObject and T:Newtonsoft.Json.Linq.JArray instances one at a time programatically.

Quickly Create JSON Object from Anonymous Object with Json.NET , Since I got my data on the fly (think parsing some other data structures and you have lots of anonymous results), I didn't want to create classes for  In this article, you will learn how to create JSON in C#. JavaScript Object Notation (JSON) is a lightweight data-interchange format. JSON creation and read of JSON string is very easy. In Web technology, nowadays people transfer and receive the data in this format. Even MONGO DB stores the data in JSON format.

JSON Creation: How to Create JSON Objects Using C# Code, In this tutorial, we will discuss the ways in which a user can create JSON object using C# code. We will be using json.net framework for  It can be useful when dealing with XML or JSON for quickly setting up a type to program against instead of always having to create data transfer objects. The ability for ExpandoObject to support data binding through INotifyPropertyChanged is a huge win for anyone using WPF, MVC, or any other binding framework in .NET as it allows you to use these “objects on the fly” as well as other statically typed classes.

JObject Class, It represents a JSON Object. It helps to parse JSON data and apply querying (LINQ) to filter out required data. Consume a JSON string (such as the following) in a C# program, hopefully creating some sort of dynamic object on the fly that we can work with like any other C# object, and then doing something with the object: saving it in database, sending it elsewhere or rendering to a screen.

Comments
  • You should get double points for the artist / album selection!
  • Perfect! Exactly what I was looking for, completely forgot about dynamic.
  • I get 'Newtonsoft.Json.Linq.JObject' does not contain a definition for 'Date' error when I try to run your code. The way I could make it work is change the first line to: dynamic jsonExpando = new ExpandoObject(); and add a line after your code: JObject jsonObject = JObject.FromObject(jsonExpando);
  • If you want to add a List<> to your Json object, you need to do something like jsonObject.list = JToken.FromObject(mylist);.
  • You could use combination of index and property notation in case you hit field name having special character e.g. Create-Year". You will not b able to write jsonObject.Create-Year = 1995, but can use following. jsonObject["Create-Year"] = 1995; jsonObject.Artist = "2Pac";
  • JObject.FromObject should be marked as the correct answer. Thanks.
  • I think JObject.FromObject won't work if there are properties with special characters like -.
  • The last one is definitively the best syntax to write json in c#.
  • see stackoverflow.com/questions/51015036/… for how to do this with collections as well
  • How does this answer the question?
  • @Enigmativity, The point I am making is, you can use index notation and property notation together. i.e. obj[x] =x1; obj.y = y1 can be used in the same code. The combination of dynamic keyword and index notation answers the questions. No other answer has mentions this. Possibly, this should be comment than a answer.
  • I just think that the question is about not using magic strings, but this answer is giving him that.
  • @Enigmativity, dynamic keyword just fools the compiler. So it's no different than arbitrary string. object of dynmaic type is not strongly typed. It's just a syntactic sugar. If the underlying object doesn't have property it will failed runtime. but you just cannot use properties if the name of property contains special characters e.g. 99BottlesOfBeer, namespace, It’s-All-Over. So in those cases, we can use indexed properties. Other answer make you think that it's one or other, but you can mix and match property and index.
  • you're not actually using the library newtonsoft here