How to Generate Structured JSON in WinUI 3 with C#

How to Generate Structured JSON in WinUI 3 with C#

When you ask an AI model for information, the response normally comes back as free-form text. That works well for chat applications, but it becomes difficult when your WinUI 3 application needs to consume the response as structured data.

Instead of receiving:

Alice is 30 years old and works as a software engineer.

your application may need:

{
  "name": "Alice",
  "age": 30,
  "occupation": "software engineer"
}

Windows App SDK 2.3.1 introduced a Structured JSON Output API that lets developers provide a JSON Schema and constrain the generated language-model response to that structure.

The API You Need

The API is GenerateStructuredJsonResponseAsync().

The basic process is:

  1. Make sure the language model is ready.
  2. Create the language model.
  3. Define your JSON Schema.
  4. Generate the structured response.
  5. Check the response status.
  6. Deserialize the JSON into your C# model.
using Microsoft.Windows.AI;
using Microsoft.Windows.AI.Text;

if (LanguageModel.GetReadyState() == AIFeatureReadyState.NotReady)
{
    await LanguageModel.EnsureReadyAsync();
}

using LanguageModel languageModel =
    await LanguageModel.CreateAsync();

var experimentalModel =
    new LanguageModelExperimental(languageModel);

string prompt =
    "Give me information about a 30-year-old software engineer named Alice.";

string jsonSchema = """
{
    "type": "object",
    "properties": {
        "name": {
            "type": "string"
        },
        "age": {
            "type": "integer"
        },
        "occupation": {
            "type": "string"
        }
    },
    "required": [
        "name",
        "age",
        "occupation"
    ]
}
""";

var options = new LanguageModelOptionsExperimental();

var result =
    await experimentalModel.GenerateStructuredJsonResponseAsync(
        prompt,
        jsonSchema,
        options);

if (result.Status == LanguageModelResponseStatus.Complete)
{
    string json = result.Text;

    // Process the JSON here
}

Why Use a JSON Schema?

The JSON Schema defines the structure your application expects from the AI response.

{
    "type": "object",
    "properties": {
        "name": {
            "type": "string"
        },
        "age": {
            "type": "integer"
        },
        "occupation": {
            "type": "string"
        }
    },
    "required": [
        "name",
        "age",
        "occupation"
    ]
}

This is more reliable than asking the model to simply "return JSON" and then trying to parse an unpredictable response.

Deserialize the Result into C#

Create a normal C# model:

public class Person
{
    public string Name { get; set; } = string.Empty;

    public int Age { get; set; }

    public string Occupation { get; set; } = string.Empty;
}

Then deserialize the generated JSON:

using System.Text.Json;

Person? person =
    JsonSerializer.Deserialize<Person>(result.Text);

Always Check the Response Status

Don't immediately assume that the response was successfully generated.

if (result.Status == LanguageModelResponseStatus.Complete)
{
    Person? person =
        JsonSerializer.Deserialize<Person>(result.Text);
}
else
{
    // Handle generation failure
}

For production applications, you should also handle invalid schema input.

try
{
    var result =
        await experimentalModel.GenerateStructuredJsonResponseAsync(
            prompt,
            jsonSchema,
            options);

    if (result.Status == LanguageModelResponseStatus.Complete)
    {
        // Process JSON
    }
}
catch (ArgumentException)
{
    // Invalid JSON Schema
}

Where Can You Use It?

  • Document information extraction
  • OCR processing
  • AI-powered search
  • Local AI assistants
  • Data classification
  • Automatic form filling
  • Invoice processing
  • Content categorization

Example: Extracting Invoice Data

Imagine a WinUI application that reads an invoice.

Instead of asking AI to summarize the invoice as plain text, you could request:

{
    "vendor": "Example Company",
    "invoiceNumber": "INV-1001",
    "total": 1250.50,
    "currency": "USD"
}

Your C# application can then deserialize the result into an Invoice model and use it normally throughout the application.

Check Your Windows App SDK Version

Windows App SDK is updated independently from the Windows operating system and Windows SDK. Windows App SDK 2.3.1 is currently listed by Microsoft as the latest stable release.

Before using newly introduced APIs, check the version referenced by your project.

<PackageReference
    Include="Microsoft.WindowsAppSDK"
    Version="2.3.1" />

Use the version appropriate for your project's supported configuration rather than changing a production project without testing.

Conclusion

Structured JSON Output solves a practical problem when integrating AI with WinUI 3 applications.

Instead of receiving unpredictable natural-language responses and writing custom parsing logic, you define the structure your application needs and generate JSON against that schema.

With Windows App SDK 2.3.1, GenerateStructuredJsonResponseAsync() provides a useful way to connect AI responses with normal C# models, databases, and UI controls.

Frequently Asked Questions

What is Structured JSON Output?

Structured JSON Output allows an AI language model response to be constrained using a developer-provided JSON Schema.

Which Windows App SDK version added this API?

The Structured JSON Output API was added in Windows App SDK 2.3.1.

Can the response be deserialized into a C# object?

Yes. After receiving a successful response, you can use System.Text.Json to deserialize the JSON into a C# model.

Why use JSON Schema instead of asking AI for JSON?

A schema gives your application a defined structure instead of relying on the model to follow a formatting instruction in plain text.

Microsoft References

CF

Written by DEVINFOTECH Technical Team

Verified file conversion guides, technical specs, and troubleshooting solutions engineered for Windows desktop users.

Comments

← Newer Posts Older Posts →

Stay Ahead in Tech & Productivity

Join 15,000+ Windows power users receiving weekly document conversion hacks, error fix tutorials, and exclusive desktop software updates directly to your inbox.

Action completed successfully!