4
Answers

Deserialize Json array object

Yang Zhang

Yang Zhang

Oct 26
571
1

Hi, I am trying to deserilize the below sample json, however, it seems that the list doesn't hold all the data in one object. Please advise.

internal class Program
{
    static void Main(string[] args)
    {

        string jsonString = @"[
            {
            ""userid"": ""0001"",
            ""name"": ""Jake1"",
            ""transfers"": [
                { ""recordsnumber"": ""5001"" },
                { ""recordsname"": ""test"" },
                { ""tmpbox"": ""5005"" },
                { ""ddate"": ""10/23/2024"" },
                { ""fromdate"": ""10/23/2024"" },
                { ""todate"": ""10/23/2024"" },
                { ""range"": ""5004"" }
            ]
            },
            {
            ""userid"": ""0002"",
            ""name"": ""Jake2"",
            ""transfers"": [
                { ""recordsnumber"": ""5001"" },
                { ""recordsname"": ""test"" },
                { ""tmpbox"": ""5005"" },
                { ""ddate"": ""10/23/2024"" },
                { ""fromdate"": ""10/23/2024"" },
                { ""todate"": ""10/23/2024"" },
                { ""range"": ""range"" }
            ]
            }
        ]";
        List<TransferTempRecords> tempRecords = ParseJsonFromString(jsonString);
    }
    public static List<TransferTempRecords> ParseJsonFromString(string jsonString)
    {
        try
        {
            return JsonSerializer.Deserialize<List<TransferTempRecords>>(jsonString);
        }
        catch (JsonException ex)
        {
            Console.WriteLine($"Error parsing JSON: {ex.Message}");
            return null;
        }
    }
}

public class TransferTempRecords
{
    public string userid { get; set; }
    public string name { get; set; }
    public List<Transfer> transfers { get; set; }
}

public class Transfer
{
    public string recordsnumber { get; set; }
    public string recordsname { get; set; }
    public string tmpbox { get; set; }
    public string ddate { get; set; }
    public string fromdate { get; set; }
    public string todate { get; set; }
    public string range { get; set; }
}
C#
Answers (4)
3
Jignesh Kumar

Jignesh Kumar

30 39.5k 2.9m Oct 29

Hello,

As per your code debug snippet, you need to do below changes in your code,

using System;
using System.Collections.Generic;
using System.Text.Json;

internal class Program
{
    static void Main(string[] args)
    {
        string jsonString = @"[
            {
                ""userid"": ""0001"",
                ""name"": ""Jake1"",
                ""transfers"": [
                    {
                        ""recordsnumber"": ""5001"",
                        ""recordsname"": ""test"",
                        ""tmpbox"": ""5005"",
                        ""ddate"": ""10/23/2024"",
                        ""fromdate"": ""10/23/2024"",
                        ""todate"": ""10/23/2024"",
                        ""range"": ""5004""
                    }
                ]
            },
            {
                ""userid"": ""0002"",
                ""name"": ""Jake2"",
                ""transfers"": [
                    {
                        ""recordsnumber"": ""5001"",
                        ""recordsname"": ""test"",
                        ""tmpbox"": ""5005"",
                        ""ddate"": ""10/23/2024"",
                        ""fromdate"": ""10/23/2024"",
                        ""todate"": ""10/23/2024"",
                        ""range"": ""range""
                    }
                ]
            }
        ]";
        List<TransferTempRecords> tempRecords = ParseJsonFromString(jsonString);

        // Optional: Print results to verify
        foreach (var record in tempRecords)
        {
            Console.WriteLine($"User: {record.name}, UserId: {record.userid}");
            foreach (var transfer in record.transfers)
            {
                Console.WriteLine($"  Transfer Record Number: {transfer.recordsnumber}");
            }
        }
    }

    public static List<TransferTempRecords> ParseJsonFromString(string jsonString)
    {
        try
        {
            return JsonSerializer.Deserialize<List<TransferTempRecords>>(jsonString);
        }
        catch (JsonException ex)
        {
            Console.WriteLine($"Error parsing JSON: {ex.Message}");
            return null;
        }
    }
}

public class TransferTempRecords
{
    public string userid { get; set; }
    public string name { get; set; }
    public List<Transfer> transfers { get; set; }
}

public class Transfer
{
    public string recordsnumber { get; set; }
    public string recordsname { get; set; }
    public string tmpbox { get; set; }
    public string ddate { get; set; }
    public string fromdate { get; set; }
    public string todate { get; set; }
    public string range { get; set; }
}
3
Vijay Pratap Singh

Vijay Pratap Singh

310 6.1k 524.7k Oct 27

The JSON structure you're working with will not deserialize properly because the objects within the transfers array do not have a consistent structure. In the JSON, each transfers array item is a separate object with different properties, while the  Transfer class expects a single object with all properties present.
Replace the Transfer class with a dictionary to handle dynamic key-value pairs in the transfers array.

using System;
using System.Collections.Generic;
using System.Text.Json;

internal class Program
{
    static void Main(string[] args)
    {
        string jsonString = @"[
            {
                ""userid"": ""0001"",
                ""name"": ""Jake1"",
                ""transfers"": [
                    { ""recordsnumber"": ""5001"" },
                    { ""recordsname"": ""test"" },
                    { ""tmpbox"": ""5005"" },
                    { ""ddate"": ""10/23/2024"" },
                    { ""fromdate"": ""10/23/2024"" },
                    { ""todate"": ""10/23/2024"" },
                    { ""range"": ""5004"" }
                ]
            },
            {
                ""userid"": ""0002"",
                ""name"": ""Jake2"",
                ""transfers"": [
                    { ""recordsnumber"": ""5001"" },
                    { ""recordsname"": ""test"" },
                    { ""tmpbox"": ""5005"" },
                    { ""ddate"": ""10/23/2024"" },
                    { ""fromdate"": ""10/23/2024"" },
                    { ""todate"": ""10/23/2024"" },
                    { ""range"": ""range"" }
                ]
            }
        ]";

        List<TransferTempRecords> tempRecords = ParseJsonFromString(jsonString);
        
        // Output the result to check if parsing was successful
        foreach (var record in tempRecords)
        {
            Console.WriteLine($"UserID: {record.userid}, Name: {record.name}");
            foreach (var transfer in record.transfers)
            {
                foreach (var kvp in transfer)
                {
                    Console.WriteLine($"  {kvp.Key}: {kvp.Value}");
                }
            }
        }
    }

    public static List<TransferTempRecords> ParseJsonFromString(string jsonString)
    {
        try
        {
            return JsonSerializer.Deserialize<List<TransferTempRecords>>(jsonString);
        }
        catch (JsonException ex)
        {
            Console.WriteLine($"Error parsing JSON: {ex.Message}");
            return null;
        }
    }
}

public class TransferTempRecords
{
    public string userid { get; set; }
    public string name { get; set; }
    public List<Dictionary<string, string>> transfers { get; set; } // Change to List of Dictionary
}

Hope this will help.

2
Asma Khalid

Asma Khalid

112 16.8k 9.8m Nov 01

If you have sample JSON then copy it. Next inside visual studio, goto Edit -> Paste Special -> Paste JSON as Classes This will create an object mapper for your JSON. Adjust the name and data type if needed. Now, you have exact object mapper as your sample json, no room for errors. But, if your issue still presist, then this means the issue is with your data not object mapper.

1
Aman Gupta

Aman Gupta

37 35.2k 2.5m Nov 04

Hi Yang,

The issue you're encountering is due to the structure of the JSON data. In your JSON, the transfers array contains multiple objects, each with a single property. This means that the transfers array does not directly map to the Transfer class as you've defined it. Instead, you need a way to represent each property of the Transfer class within a single object in the transfers array.

To resolve this, you have two main options:

Option 1: Change the JSON Structure

If you have control over the JSON structure, you can change it so that each transfers entry is a single object that contains all the properties. Here’s how the modified JSON would look:

With this structure, each transfer is a single object containing all the properties, which will match your Transfer class.

Option 2: Modify the Data Model to Match the JSON Structure

If you cannot change the JSON structure, you will need to create a different data model to deserialize the JSON properly. Here’s how you can do it:

  1. Create a class to represent the individual transfer properties:
    public class TransferProperties
    {
        public string recordsnumber { get; set; }
        public string recordsname { get; set; }
        public string tmpbox { get; set; }
        public string ddate { get; set; }
        public string fromdate { get; set; }
        public string todate { get; set; }
        public string range { get; set; }
    }
  2. Modify the TransferTempRecords class to hold a list of TransferProperties:
    public class TransferTempRecords
    {
        public string userid { get; set; }
        public string name { get; set; }
        public List<TransferProperties> transfers { get; set; }
    }
  3. Deserialize the JSON as before:

    Now, you can deserialize the original JSON without any change

    public static List<TransferTempRecords> ParseJsonFromString(string jsonString)
    {
        try
        {
            return JsonSerializer.Deserialize<List<TransferTempRecords>>(jsonString);
        }
        catch (JsonException ex)
        {
            Console.WriteLine($"Error parsing JSON: {ex.Message}");
            return null;
        }
    }

Summary

  • If you can modify the JSON structure, it's best to make each transfer a single object containing all relevant properties.
  • If you cannot change the JSON, modify your data model to accommodate the current structure, which involves creating a new class to represent the properties of each transfer.

Choose the option that best fits your situation.