Json.NET
JObject
object conversion
JSON serialization
C# programming

Convert object of any type to JObject with Json.NET

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

JObject is useful when you need dynamic JSON manipulation after taking an ordinary .NET object and turning it into a token tree. The straightforward call is JObject.FromObject, but a robust solution also needs to handle nulls, existing JToken values, serializer settings, and cases where the root value is not actually an object.

The Normal Case: JObject.FromObject

For plain classes or anonymous objects, Json.NET already gives you the core API.

csharp
1using Newtonsoft.Json.Linq;
2
3var person = new
4{
5    Id = 42,
6    Name = "Ava",
7    Active = true
8};
9
10JObject json = JObject.FromObject(person);
11Console.WriteLine(json.ToString());

This works because the root value is object-shaped. Json.NET reflects over the properties and creates a JObject tree.

A Reusable Helper Method

In real code, conversion logic is cleaner when centralized.

csharp
1using Newtonsoft.Json;
2using Newtonsoft.Json.Linq;
3
4public static class JsonHelpers
5{
6    public static JObject ToJObject(object? value, JsonSerializer? serializer = null)
7    {
8        if (value is null)
9        {
10            return new JObject();
11        }
12
13        if (value is JObject existingObject)
14        {
15            return existingObject;
16        }
17
18        if (value is JToken token)
19        {
20            return token as JObject ?? new JObject(new JProperty("value", token));
21        }
22
23        serializer ??= JsonSerializer.CreateDefault();
24        return JObject.FromObject(value, serializer);
25    }
26}

This gives you a single entry point and avoids double-converting token types that are already JSON-aware.

Why Existing JToken Values Need Special Handling

JObject.FromObject is meant for CLR objects, not for every possible JSON token shape. If the caller passes a JArray, a primitive JValue, or some other JToken, you need to decide what object shape should result.

That is why the helper above wraps non-object tokens under a value property.

csharp
1using Newtonsoft.Json.Linq;
2
3JArray items = new JArray(1, 2, 3);
4JObject wrapped = JsonHelpers.ToJObject(items);
5
6Console.WriteLine(wrapped.ToString());

Whether wrapping is the right choice depends on your contract. The key point is that arrays and primitives are not JObject roots by themselves.

Serializer Settings Matter

FromObject uses serializer rules. If naming strategy, null handling, enum formatting, or converters matter to your API, create the serializer explicitly.

csharp
1using Newtonsoft.Json;
2using Newtonsoft.Json.Serialization;
3using Newtonsoft.Json.Linq;
4
5var serializer = JsonSerializer.Create(new JsonSerializerSettings
6{
7    NullValueHandling = NullValueHandling.Ignore,
8    ContractResolver = new CamelCasePropertyNamesContractResolver()
9});
10
11var payload = new
12{
13    FirstName = "Ava",
14    MiddleName = (string?)null
15};
16
17JObject json = JObject.FromObject(payload, serializer);
18Console.WriteLine(json.ToString());

With those settings, MiddleName is omitted and property names become camelCase.

Dynamic Mutation After Conversion

The main reason people choose JObject over ordinary serialization is that they want to inspect or alter the JSON dynamically.

csharp
1using Newtonsoft.Json.Linq;
2
3var order = new { OrderId = 1001, Amount = 12.50m };
4JObject json = JObject.FromObject(order);
5
6json["currency"] = "USD";
7json["metadata"] = new JObject
8{
9    ["source"] = "api"
10};
11
12Console.WriteLine(json.ToString());

This is a good fit for integration layers, gateways, logging pipelines, or schema-translation steps.

When JObject Is the Wrong Tool

If the JSON shape is fixed and well-known, a strongly typed DTO is usually better. JObject is convenient, but it moves errors from compile time to runtime.

Use JObject when:

  • the payload shape is partially dynamic
  • you are transforming third-party JSON
  • you need selective inspection without defining many small DTOs

Do not use it by default for ordinary application-domain models if strong types would be clearer.

Common Pitfalls

The biggest mistake is assuming every value can become a JObject directly. Arrays, primitives, and nulls need special treatment.

Another mistake is forgetting that serializer settings affect the resulting JSON. Two services using different settings can produce different property names or null behavior from the same CLR object.

A third issue is mutating nested properties without null checks. SelectToken or index access can return null, and dynamic JSON code should handle that deliberately.

Finally, overusing JObject can make code harder to maintain than simply defining a proper model class.

Summary

  • 'JObject.FromObject is the standard Json.NET way to convert object-shaped values.'
  • Wrap conversion in a helper if you need null and JToken handling in one place.
  • Existing JObject values should usually be reused, not reserialized.
  • Serializer settings control naming, null handling, and other output details.
  • 'JObject is ideal for dynamic transformation, not for every JSON use case.'
  • Treat array roots and primitive roots explicitly instead of assuming they are objects.

Course illustration
Course illustration

All Rights Reserved.