Deserialize JSON array(or list) in C#

Deserialize JSON array(or list) in C#

To deserialize a JSON array (or list) in C# into a corresponding .NET data structure, you can use the System.Text.Json or Newtonsoft.Json libraries, depending on the .NET version you are working with. Both libraries provide easy-to-use methods for parsing JSON data.

Here are examples of how to deserialize a JSON array using both libraries:

  • Using System.Text.Json (.NET Core 3.1 and later):
using System;
using System.Text.Json;

class Program
{
    static void Main()
    {
        string json = @"[1, 2, 3, 4, 5]"; // JSON array as a string

        // Deserialize the JSON array into a List<int>
        var integers = JsonSerializer.Deserialize<List<int>>(json);

        // Output the result
        foreach (int number in integers)
        {
            Console.WriteLine(number);
        }
    }
}
  • Using Newtonsoft.Json (Newtonsoft.Json):
using System;
using Newtonsoft.Json;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        string json = @"[1, 2, 3, 4, 5]"; // JSON array as a string

        // Deserialize the JSON array into a List<int>
        var integers = JsonConvert.DeserializeObject<List<int>>(json);

        // Output the result
        foreach (int number in integers)
        {
            Console.WriteLine(number);
        }
    }
}

Both examples demonstrate how to deserialize a JSON array into a List<int> containing the integers 1 to 5. You can replace the int with other data types or custom classes to deserialize more complex JSON structures.

Note: If you are using .NET Core 3.0 or later, Microsoft recommends using System.Text.Json for serialization and deserialization due to its performance and ease of use. However, if you are working with an older .NET version or you prefer to use Newtonsoft.Json (Newtonsoft.Json) for any reason, it is still a widely-used and reliable library for JSON processing in .NET.

Examples

  1. "C# Deserialize JSON Array using JSON.NET"

    • Code Implementation:
      using Newtonsoft.Json;
      using System;
      using System.Collections.Generic;
      
      var jsonArray = "[{\"Name\":\"John\",\"Age\":25},{\"Name\":\"Alice\",\"Age\":30}]";
      var persons = JsonConvert.DeserializeObject<List<Person>>(jsonArray);
      
    • Description: Deserializes a JSON array (jsonArray) into a list of C# objects (Person) using JSON.NET's JsonConvert.DeserializeObject method.
  2. "C# Deserialize JSON Array with Anonymous Type"

    • Code Implementation:
      using Newtonsoft.Json;
      using System;
      
      var jsonArray = "[{\"Name\":\"John\",\"Age\":25},{\"Name\":\"Alice\",\"Age\":30}]";
      var persons = JsonConvert.DeserializeAnonymousType(jsonArray, new[] { new { Name = "", Age = 0 } });
      
    • Description: Deserializes a JSON array (jsonArray) into an array of anonymous types using JSON.NET's JsonConvert.DeserializeAnonymousType method.
  3. "C# Deserialize JSON Array with Dynamic Object"

    • Code Implementation:
      using Newtonsoft.Json;
      using System;
      
      var jsonArray = "[{\"Name\":\"John\",\"Age\":25},{\"Name\":\"Alice\",\"Age\":30}]";
      dynamic persons = JsonConvert.DeserializeObject(jsonArray);
      
    • Description: Deserializes a JSON array (jsonArray) into a dynamic object using JSON.NET, allowing access to properties without a predefined class structure.
  4. "C# Deserialize JSON Array with LINQ to JSON"

    • Code Implementation:
      using Newtonsoft.Json.Linq;
      using System;
      
      var jsonArray = "[{\"Name\":\"John\",\"Age\":25},{\"Name\":\"Alice\",\"Age\":30}]";
      var persons = JArray.Parse(jsonArray).ToObject<List<Person>>();
      
    • Description: Parses a JSON array (jsonArray) using Newtonsoft.Json.Linq.JArray and converts it into a list of C# objects (Person).
  5. "C# Deserialize JSON Array with System.Text.Json"

    • Code Implementation:
      using System.Text.Json;
      using System;
      
      var jsonArray = "[{\"Name\":\"John\",\"Age\":25},{\"Name\":\"Alice\",\"Age\":30}]";
      var persons = JsonSerializer.Deserialize<List<Person>>(jsonArray);
      
    • Description: Deserializes a JSON array (jsonArray) into a list of C# objects (Person) using the System.Text.Json.JsonSerializer class.
  6. "C# Deserialize JSON Array with Custom Converter"

    • Code Implementation:
      using Newtonsoft.Json;
      using Newtonsoft.Json.Converters;
      using System;
      
      public class CustomListConverter<T> : JsonConverter<List<T>>
      {
          public override List<T> ReadJson(JsonReader reader, Type objectType, List<T> existingValue, bool hasExistingValue, JsonSerializer serializer)
          {
              return serializer.Deserialize<List<T>>(reader);
          }
      
          public override void WriteJson(JsonWriter writer, List<T> value, JsonSerializer serializer)
          {
              serializer.Serialize(writer, value);
          }
      }
      
      var jsonArray = "[{\"Name\":\"John\",\"Age\":25},{\"Name\":\"Alice\",\"Age\":30}]";
      var persons = JsonConvert.DeserializeObject<List<Person>>(jsonArray, new CustomListConverter<Person>());
      
    • Description: Deserializes a JSON array (jsonArray) into a list of C# objects (Person) using a custom converter with JSON.NET.
  7. "C# Deserialize JSON Array with Error Handling"

    • Code Implementation:
      using Newtonsoft.Json;
      using System;
      
      var jsonArray = "[{\"Name\":\"John\",\"Age\":25},{\"Name\":\"Alice\",\"Age\":\"InvalidAge\"}]";
      try
      {
          var persons = JsonConvert.DeserializeObject<List<Person>>(jsonArray);
      }
      catch (JsonException ex)
      {
          Console.WriteLine($"Error during deserialization: {ex.Message}");
      }
      
    • Description: Adds error handling to the deserialization process using try-catch blocks to handle potential JSON parsing errors within the array.
  8. "C# Deserialize JSON Array with Custom Property Names"

    • Code Implementation:
      using Newtonsoft.Json;
      using System;
      
      var jsonArray = "[{\"full_name\":\"John Doe\",\"user_age\":25},{\"full_name\":\"Alice Smith\",\"user_age\":30}]";
      var persons = JsonConvert.DeserializeObject<List<Person>>(jsonArray, new JsonSerializerSettings
      {
          ContractResolver = new DefaultContractResolver
          {
              NamingStrategy = new SnakeCaseNamingStrategy()
          }
      });
      
    • Description: Deserializes a JSON array (jsonArray) with custom property names into a list of C# objects (Person) using a custom contract resolver with JSON.NET.
  9. "C# Deserialize JSON Array with Type Information"

    • Code Implementation:
      using Newtonsoft.Json;
      using System;
      
      var jsonArray = "[{\"$type\":\"Namespace.Person, Assembly\",\"Name\":\"John\",\"Age\":25}]";
      var persons = JsonConvert.DeserializeObject<List<Person>>(jsonArray, new JsonSerializerSettings
      {
          TypeNameHandling = TypeNameHandling.Auto
      });
      
    • Description: Deserializes a JSON array (jsonArray) with type information into a list of C# objects (Person) using type name handling with JSON.NET.
  10. "C# Deserialize JSON Array with Nullable Types"

    • Code Implementation:
      using Newtonsoft.Json;
      using System;
      
      var jsonArray = "[{\"Name\":\"John\",\"Age\":25},{\"Name\":\"Alice\",\"Age\":null}]";
      var persons = JsonConvert.DeserializeObject<List<Person>>(jsonArray);
      
    • Description: Deserializes a JSON array (jsonArray) with nullable types into a list of C# objects (Person) using JSON.NET.

More Tags

setbackground bitmask enum-flags cluster-analysis state syntastic for-loop fileinputstream adb http-proxy

More C# Questions

More Entertainment Anecdotes Calculators

More Gardening and crops Calculators

More Chemical thermodynamics Calculators

More Cat Calculators