.NET MAUI JSON Deserialization with System Text Json and Newtonsoft Json Step by step Implementation and Top 10 Questions and Answers
 Last Update: April 01, 2025      18 mins read      Difficulty-Level: beginner

.NET MAUI JSON Deserialization with System.Text.Json and Newtonsoft.Json

Developing modern cross-platform applications using .NET MAUI (Multi-platform App UI) requires efficient handling of data, often in the form of JSON. JSON (JavaScript Object Notation) is a lightweight, text-based, data interchange format widely used for data transmission between applications. In .NET MAUI, JSON deserialization plays a crucial role in converting JSON strings into .NET objects, which can then be manipulated and used within the application. This article will explore two popular JSON deserialization libraries in .NET MAUI: System.Text.Json and Newtonsoft.Json.

System.Text.Json

Introduction:

  • System.Text.Json is part of the .NET Core libraries and has been integrated into .NET MAUI out-of-the-box. It provides a high-performance, low-allocating, UTF-8-based serializer and deserializer for JSON.
  • It is the recommended library for new applications due to its performance benefits and alignment with modern .NET standards.

Key Features:

  1. UTF-8 Support: System.Text.Json can read and write JSON data using UTF-8 encoding, which is generally more efficient than UTF-16.
  2. Low Memory Allocation: It minimizes memory allocations during JSON parsing, which is beneficial for performance-critical applications.
  3. Built-in: No additional package installation is required as it is part of the .NET framework.

Basic Usage:

  • To deserialize JSON using System.Text.Json, first, define your data model classes that match the JSON structure.
public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string Email { get; set; }
}
  • Then, deserialize the JSON string into a Person object.
string jsonString = "{\"Name\":\"John Doe\",\"Age\":30,\"Email\":\"john.doe@example.com\"}";
Person person = JsonSerializer.Deserialize<Person>(jsonString);

Advanced Usage:

  • You can customize the deserialization process using JsonSerializerOptions. For example, to ignore case sensitivity:
var options = new JsonSerializerOptions
{
    PropertyNameCaseInsensitive = true
};

Person person = JsonSerializer.Deserialize<Person>(jsonString, options);

Newtonsoft.Json (Json.NET)

Introduction:

  • Newtonsoft.Json (also known as Json.NET) is a widely used, feature-rich JSON framework for .NET. It has been around for many years and supports a variety of .NET platforms, including .NET MAUI.
  • While System.Text.Json is the modern choice, Newtonsoft.Json offers more advanced features and better support for complex data types, making it a valuable tool in many development scenarios.

Installation:

  • To use Newtonsoft.Json in your .NET MAUI project, you need to install the package from NuGet:
dotnet add package Newtonsoft.Json

Basic Usage:

  • Similar to System.Text.Json, you first define your data model classes.
public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string Email { get; set; }
}
  • Then, deserialize the JSON string into a Person object.
string jsonString = "{\"Name\":\"John Doe\",\"Age\":30,\"Email\":\"john.doe@example.com\"}";
Person person = JsonConvert.DeserializeObject<Person>(jsonString);

Advanced Usage:

  • Newtonsoft.Json provides extensive customization options. For example, to handle complex types with custom converters:
public class CustomDateTimeConverter : JsonConverter<DateTime>
{
    private const string DateFormat = "yyyy-MM-dd HH:mm:ss";

    public override DateTime ReadJson(JsonReader reader, Type objectType, DateTime existingValue, bool hasExistingValue, JsonSerializer serializer)
    {
        return DateTime.ParseExact((string)reader.Value, DateFormat, CultureInfo.InvariantCulture);
    }

    public override void WriteJson(JsonWriter writer, DateTime value, JsonSerializer serializer)
    {
        writer.WriteValue(value.ToString(DateFormat, CultureInfo.InvariantCulture));
    }
}

string jsonString = "{\"Name\":\"John Doe\",\"Age\":30,\"Email\":\"john.doe@example.com\",\"BirthDate\":\"1992-05-15 00:00:00\"}";
var settings = new JsonSerializerSettings
{
    Converters = new List<JsonConverter> { new CustomDateTimeConverter() }
};
Person person = JsonConvert.DeserializeObject<Person>(jsonString, settings);

Comparison:

| Feature | System.Text.Json | Newtonsoft.Json | |-----------------------------------|-------------------------------------------------------|-------------------------------------------------------------| | Performance | High-performance, low memory allocation | Generally slower due to higher memory usage | | Built-in Support | Part of .NET Core framework | Requires NuGet package installation | | Features | Basic deserialization, UTF-8 support | Extensive features, custom converters, annotations | | UTF-8 Support | Native UTF-8 support | Can use UTF-8 with additional configuration | | Complex Type Handling | Limited direct support for complex types | Excellent support for custom serialization of complex types | | Documentation | Comprehensive documentation in official .NET docs | Extensive community and official documentation | | Compatibility | Modern .NET platforms (including .NET MAUI) | Supports a wide range of .NET platforms, including legacy ones|

Conclusion

Choosing between System.Text.Json and Newtonsoft.Json in .NET MAUI depends on the specific needs of your application. For performance-critical applications or those targeting modern .NET platforms, System.Text.Json is the recommended choice. On the other hand, if you require advanced serialization/deserialization features or need better compatibility with complex data types, Newtonsoft.Json is an excellent option. Both libraries are powerful tools in the .NET ecosystem and will help you efficiently handle JSON data in your .NET MAUI applications.

.NET MAUI JSON Deserialization with System.Text.Json and Newtonsoft.Json: Examples, Set Route, and Run the Application – Step by Step for Beginners

When working with data in .NET MAUI (Multi-platform App UI) applications, JSON deserialization is a common requirement. JSON (JavaScript Object Notation) is a widely used format for data interchange that is both lightweight and easy to read/write. This guide will walk you through setting up JSON deserialization using both System.Text.Json and Newtonsoft.Json libraries in a .NET MAUI application, from setting the route in the app to running the application and seeing the data flow.


Prerequisites

Before you start, ensure you have:

  • Visual Studio installed with the .NET MAUI workload.
  • Basic understanding of C# and .NET MAUI concepts.
  • Familiarity with JSON format.

Example JSON

We'll use the following sample JSON data for demonstration purposes:

{
    "id": 1,
    "name": "John Doe",
    "email": "john.doe@example.com",
    "phone": "1234567890",
    "is_active": true,
    "address": {
        "street": "123 Elm St",
        "city": "Somewhere",
        "zip_code": "12345"
    },
    "skills": ["C#", "Java", ".NET"]
}

Step 1: Create a New .NET MAUI Project

  1. Open Visual Studio.
  2. Create a new project:
    • Go to File > New > Project.
    • Find and select .NET MAUI App.
    • Configure your project with a name, location, and solution name, then click Create.

Step 2: Add Models to the Project

We'll create a few C# classes that correspond to the JSON structure.

  1. Add a new folder named Models to your project.
  2. Add a new class named User.cs in the Models folder with the following code:
using System.Collections.Generic;

namespace YourApp.Models
{
    public class User
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
        public string Phone { get; set; }
        public bool IsActive { get; set; }
        public Address Address { get; set; }
        public List<string> Skills { get; set; }
    }

    public class Address
    {
        public string Street { get; set; }
        public string City { get; set; }
        public string ZipCode { get; set; }
    }
}

Step 3: Configure JSON Data Source

For demonstration, we'll use a string to represent the JSON data. In a real-world scenario, this data would likely come from a web API.

  1. Add a new static class named JsonDataService.cs outside the Models folder, but within the project:
using System.Text.Json;

namespace YourApp
{
    public static class JsonDataService
    {
        public static string SampleJsonData => @"
        {
            ""id"": 1,
            ""name"": ""John Doe"",
            ""email"": ""john.doe@example.com"",
            ""phone"": ""1234567890"",
            ""is_active"": true,
            ""address"": {
                ""street"": ""123 Elm St"",
                ""city"": ""Somewhere"",
                ""zip_code"": ""12345""
            },
            ""skills"": [""C#"", ""Java"", "".NET""]
        }";

        public static User DeserializeUser(string jsonData)
        {
            var options = new JsonSerializerOptions
            {
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
                Readable = true,
                WriteIndented = true
            };
            return JsonSerializer.Deserialize<User>(jsonData, options);
        }
    }
}

Step 4: Deserialization with Newtonsoft.Json

If you prefer using Newtonsoft.Json (also known as Json.NET), you need to install its NuGet package first.

  1. Install Newtonsoft.Json NuGet Package:

    • Go to Tools > NuGet Package Manager > Manage NuGet Packages for Solution.
    • Search for "Newtonsoft.Json" and install it for your project.
  2. Add a new static class named NewtonsoftJsonDataService.cs:

using Newtonsoft.Json;

namespace YourApp
{
    public static class NewtonsoftJsonDataService
    {
        public static User DeserializeUser(string jsonData)
        {
            var settings = new JsonSerializerSettings
            {
                PropertyNamingPolicy = SnakeCaseNamingStrategy.Instance,
                Formatting = Formatting.Indented
            };
            return JsonConvert.DeserializeObject<User>(jsonData, settings);
        }
    }
}

Step 5: Set Up a Route and Display the Data

We'll use a MainPage to demonstrate the deserialization process.

  1. Open MainPage.xaml and replace its content with a simple Label:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="YourApp.MainPage">
    <Label x:Name="DataLabel"
           Text="Deserialized Data will appear here"
           HorizontalOptions="Center"
           VerticalOptions="Center" />
</ContentPage>
  1. Open MainPage.xaml.cs and modify the constructor to deserialize JSON data and display it:
using System.Text;
using YourApp.Models;

namespace YourApp
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();

            // Using System.Text.Json
            var user = JsonDataService.DeserializeUser(JsonDataService.SampleJsonData);
            DataLabel.Text = SerializeObject(user);

            // Alternatively, using Newtonsoft.Json
            // var user = NewtonsoftJsonDataService.DeserializeUser(JsonDataService.SampleJsonData);
            // DataLabel.Text = JsonConvert.SerializeObject(user, Formatting.Indented);
        }

        private string SerializeObject(object obj)
        {
            var options = new JsonSerializerOptions
            {
                WriteIndented = true,
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase
            };
            return JsonSerializer.Serialize(obj, options);
        }
    }
}

Step 6: Run the Application

  1. Configure your target platform (e.g., Windows, Android, iOS).
  2. Press F5 to build and run the application.
  3. You should see the deserialized JSON data displayed on the screen.

Additional Notes

  • Error Handling: Always handle exceptions when working with deserialization, especially when fetching data over the network.
  • Performance: Newtonsoft.Json is generally more feature-rich and performs well for complex scenarios, while System.Text.Json is lighter and newer, ideal for simpler use cases.

This guide has demonstrated how to set up JSON deserialization in a .NET MAUI application using both System.Text.Json and Newtonsoft.Json. By following these steps, you should be able to integrate JSON parsing into your own projects effectively.

Top 10 Questions and Answers on .NET MAUI JSON Deserialization with System.Text.Json and Newtonsoft.Json

When working with .NET MAUI, handling JSON data is essential for building robust applications that can communicate with web services, APIs, and databases. With the introduction of .NET MAUI, developers have two primary options for JSON deserialization: System.Text.Json and Newtonsoft.Json (Json.NET). This guide provides answers to the top 10 questions frequently asked regarding JSON deserialization in .NET MAUI with these two libraries.

1. What are the differences between System.Text.Json and Newtonsoft.Json?

Answer: Both libraries are used for JSON serialization and deserialization, but they have notable differences:

  • Performance: System.Text.Json is generally faster and uses less memory compared to Newtonsoft.Json. It is built into .NET Core and later versions, making it a more efficient choice for high-performance scenarios.

  • Features:

    • Newtonsoft.Json offers extensive features like LINQ-to-JSON, JSON Schema, and more complex serialization scenarios. It supports various date-time formats, custom converters, and custom serialization logic.
    • System.Text.Json is more restrictive out-of-the-box but includes asynchronous methods for better performance and scalability. It supports JSON attributes directly in classes with [JsonPropertyName].
  • Usage Complexity: Newtonsoft.Json tends to be more flexible and easier to customize, although it might require more boilerplate code.

2. How do I deserialize a JSON string into a C# object using System.Text.Json in .NET MAUI?

Answer: To deserialize a JSON string into a C# object using System.Text.Json, you can use the JsonSerializer.Deserialize method. Here is an example:

using System.Text.Json;

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string Email { get; set; }
}

public void DeserializeJsonString()
{
    string jsonString = "{\"Name\":\"John Doe\",\"Age\":30,\"Email\":\"john.doe@example.com\"}";

    Person person = JsonSerializer.Deserialize<Person>(jsonString);

    Console.WriteLine($"Name: {person.Name}, Age: {person.Age}, Email: {person.Email}");
}

3. How do I deserialize a JSON string into a C# object using Newtonsoft.Json in .NET MAUI?

Answer: To deserialize a JSON string using Newtonsoft.Json, you can use the JsonConvert.DeserializeObject method. Here is an example:

using Newtonsoft.Json;

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string Email { get; set; }
}

public void DeserializeJsonString()
{
    string jsonString = "{\"Name\":\"John Doe\",\"Age\":30,\"Email\":\"john.doe@example.com\"}";

    Person person = JsonConvert.DeserializeObject<Person>(jsonString);

    Console.WriteLine($"Name: {person.Name}, Age: {person.Age}, Email: {person.Email}");
}

4. How can I handle custom JSON serialization with System.Text.Json?

Answer: For custom JSON serialization with System.Text.Json, you need to create a custom converter by inheriting from JsonConverter<T>. Here's an example:

using System.Text.Json;
using System.Text.Json.Serialization;

public class CustomDateTimeConverter : JsonConverter<DateTime>
{
    private const string dateTimeFormat = "yyyy-MM-dd HH:mm:ss";

    public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        return DateTime.ParseExact(reader.GetString(), dateTimeFormat, CultureInfo.InvariantCulture);
    }

    public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
    {
        writer.WriteStringValue(value.ToString(dateTimeFormat));
    }
}

public class Event
{
    public string Name { get; set; }
    [JsonConverter(typeof(CustomDateTimeConverter))]
    public DateTime Date { get; set; }
}

public void DeserializeWithCustomConverter()
{
    string jsonString = "{\"Name\":\"Conference\",\"Date\":\"2023-10-20 10:00:00\"}";

    Event myEvent = JsonSerializer.Deserialize<Event>(jsonString);

    Console.WriteLine($"Name: {myEvent.Name}, Date: {myEvent.Date}");
}

5. How can I handle custom JSON serialization with Newtonsoft.Json?

Answer: With Newtonsoft.Json, you can create a custom converter by inheriting from JsonConverter. Here is an example:

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

public class CustomDateTimeConverter : JsonConverter
{
    private const string dateTimeFormat = "yyyy-MM-dd HH:mm:ss";

    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(DateTime);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        JToken token = JToken.Load(reader);
        return DateTime.ParseExact(token.Value<string>(), dateTimeFormat, CultureInfo.InvariantCulture);
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        writer.WriteValue(((DateTime)value).ToString(dateTimeFormat));
    }
}

public class Event
{
    public string Name { get; set; }
    [JsonConverter(typeof(CustomDateTimeConverter))]
    public DateTime Date { get; set; }
}

public void DeserializeWithCustomConverter()
{
    string jsonString = "{\"Name\":\"Conference\",\"Date\":\"2023-10-20 10:00:00\"}";

    Event myEvent = JsonConvert.DeserializeObject<Event>(jsonString);

    Console.WriteLine($"Name: {myEvent.Name}, Date: {myEvent.Date}");
}

6. How do I handle null values during JSON deserialization with System.Text.Json?

Answer: In System.Text.Json, you can handle null values using the JsonSerializerOptions class. You can set the DefaultIgnoreCondition to IgnoreCondition.WhenWritingNull to avoid null values during serialization. For deserialization, you typically handle nulls with nullable types or default constructors.

Here is an example:

public class Person
{
    public string Name { get; set; }
    public int? Age { get; set; }
    public string Email { get; set; }
}

public void DeserializeWithNullHandling()
{
    string jsonString = "{\"Name\":\"John Doe\",\"Email\":null}";

    JsonSerializerOptions options = new JsonSerializerOptions
    {
        DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.Never
    };

    Person person = JsonSerializer.Deserialize<Person>(jsonString, options);

    Console.WriteLine($"Name: {person.Name}, Age: {person.Age}, Email: {person.Email}");
}

7. How do I handle null values during JSON deserialization with Newtonsoft.Json?

Answer: With Newtonsoft.Json, handling null values is straightforward since nullable types and default constructors handle most cases. You can also use the NullValueHandling property in JsonSerializerSettings.

Here is an example:

public class Person
{
    public string Name { get; set; }
    public int? Age { get; set; }
    public string Email { get; set; }
}

public void DeserializeWithNullHandling()
{
    string jsonString = "{\"Name\":\"John Doe\",\"Email\":null}";

    JsonSerializerSettings settings = new JsonSerializerSettings
    {
        NullValueHandling = NullValueHandling.Ignore
    };

    Person person = JsonConvert.DeserializeObject<Person>(jsonString, settings);

    Console.WriteLine($"Name: {person.Name}, Age: {person.Age}, Email: {person.Email}");
}

8. How can I deserialize a JSON array into a list of objects in .NET MAUI using System.Text.Json?

Answer: To deserialize a JSON array into a list of objects using System.Text.Json, you can use the JsonSerializer.Deserialize method with a List<T> generic type.

Here is an example:

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string Email { get; set; }
}

public void DeserializeJsonArray()
{
    string jsonArray = "[{\"Name\":\"John Doe\",\"Age\":30,\"Email\":\"john.doe@example.com\"}, {\"Name\":\"Jane Doe\",\"Age\":25,\"Email\":\"jane.doe@example.com\"}]";

    List<Person> people = JsonSerializer.Deserialize<List<Person>>(jsonArray);

    foreach (Person person in people)
    {
        Console.WriteLine($"Name: {person.Name}, Age: {person.Age}, Email: {person.Email}");
    }
}

9. How can I deserialize a JSON array into a list of objects in .NET MAUI using Newtonsoft.Json?

Answer: To deserialize a JSON array into a list of objects with Newtonsoft.Json, you can use the JsonConvert.DeserializeObject method with a List<T> generic type.

Here is an example:

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string Email { get; set; }
}

public void DeserializeJsonArray()
{
    string jsonArray = "[{\"Name\":\"John Doe\",\"Age\":30,\"Email\":\"john.doe@example.com\"}, {\"Name\":\"Jane Doe\",\"Age\":25,\"Email\":\"jane.doe@example.com\"}]";

    List<Person> people = JsonConvert.DeserializeObject<List<Person>>(jsonArray);

    foreach (Person person in people)
    {
        Console.WriteLine($"Name: {person.Name}, Age: {person.Age}, Email: {person.Email}");
    }
}

10. Which library should I use in a new .NET MAUI project: System.Text.Json or Newtonsoft.Json?

Answer: The choice between System.Text.Json and Newtonsoft.Json depends on your project's requirements:

  • Use System.Text.Json if you need maximum performance and efficiency, and you can work within its constraints. It's suitable for most straightforward serialization and deserialization scenarios in modern .NET applications.

  • Use Newtonsoft.Json if you need advanced features, extensive customization, and compatibility with older codebases. It provides more flexibility and is a well-tested, widely-used library.

Ultimately, if performance is a critical concern and your use case aligns well with System.Text.Json's capabilities, it may be the better choice. Otherwise, Newtonsoft.Json offers a broader range of features that might ease development in more complex scenarios.

By understanding these differences and capabilities, you can make an informed decision on which library to use for JSON deserialization in your .NET MAUI projects.