Table of Contents

JsonWriterExtensions Class

Definition

Namespace
Codebelt.Extensions.Newtonsoft.Json
Assemblies
Codebelt.Extensions.Newtonsoft.Json.dll
Source
src/Codebelt.Extensions.Newtonsoft.Json/JsonWriterExtensions.cs

Extension methods for the Newtonsoft.Json.JsonWriter.

public static class JsonWriterExtensions
Inheritance
JsonWriterExtensions

Examples

The following example demonstrates writing JSON objects and property names using extension methods.

using System;
using System.IO;
using Codebelt.Extensions.Newtonsoft.Json;
using Newtonsoft.Json;

namespace Examples;

class JsonWriterExtensionsExample
{
    static void Main()
    {
        using var sw = new StringWriter();
        using var jw = new JsonTextWriter(sw);
        var serializer = JsonSerializer.Create();

        jw.WriteStartObject();
        jw.WritePropertyName("user");
        jw.WriteStartObject();
        jw.WritePropertyName("name");
        jw.WriteValue("Alice");
        jw.WriteEndObject();
        
        jw.WritePropertyName("metadata");
        var metadataObject = new { version = "1.0", timestamp = DateTime.UtcNow };
        jw.WriteObject(metadataObject, serializer);
        
        jw.WriteEndObject();

        Console.WriteLine(sw.ToString());
    }
}

Methods

Name Description
WriteObject(JsonWriter, object, JsonSerializer)

Serializes the specified value and writes the JSON structure using the specified writer.

WritePropertyName(JsonWriter, string, JsonSerializer, bool)

Writes the property name of a name/value pair of a JSON object.