Deserializing a JSON array string into a C# object

Julio Bello 221 Reputation points
2021-12-23T21:41:42.26+00:00

Hi, Everybody!

I need some help… I wish to deserialize a JSON string into a C# object. I am having a most difficult time in particular with the following case.

[{"X1":"x1","Y1":"y1","Z1":"z1"},{"X2":"x2","Y2":"y2","Z2":"z2"},{"X3":"x3","Y3":"y3","Z3":"z3"},...]

How do I define a C# class that will serialize/deserialize to/from the above JSON string? I’ve tried everything I know. I even considered anonymous (i.e., implicitly typed) arrays. The problem seems that the "object" is an array… Therefore, not an object. Does anyone know how to overcome this?

I use the following method for deserializing. I don’t need help with the code. It works perfectly. I am just providing it for reference. I just want to know how to define the class (T).

private T JsonStringToObject<T>(string jsonString)
{
    using (var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)))
    {
        var dataContractJsonSerializer = new DataContractJsonSerializer(typeof(T));

        return (T)dataContractJsonSerializer.ReadObject(memoryStream);
    }
}
.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,244 questions
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,059 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,202 questions
.NET Runtime
.NET Runtime
.NET: Microsoft Technologies based on the .NET software framework.Runtime: An environment required to run apps that aren't compiled to machine language.
1,105 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Alon Fliess 256 Reputation points
    2021-12-23T22:35:06.813+00:00

    If your array continues with X4,Y4,Z4, you have a problem since, for deserializing the strong type class from the JSON, the array entries should be known. To deserialize the current JSON, use the following classes:

    public class Rootobject
    {
        public Class1[] Property1 { get; set; }
    }
    
    public class Class1
    {
        public string X1 { get; set; }
        public string Y1 { get; set; }
        public string Z1 { get; set; }
        public string X2 { get; set; }
        public string Y2 { get; set; }
        public string Z2 { get; set; }
        public string X3 { get; set; }
        public string Y3 { get; set; }
        public string Z3 { get; set; }
    }
    

    You may read the JSON dynamically instead of deserializing the array:

        using System.Text.Json.Nodes;
        var jsonString = "[{\"X1\":\"x1\",\"Y1\":\"y1\",\"Z1\":\"z1\"},{\"X2\":\"x2\",\"Y2\":\"y2\",\"Z2\":\"z2\"},{\"X3\":\"x3\",\"Y3\":\"y3\",\"Z3\":\"z3\"}]";
        var jsonObject = JsonNode.Parse(jsonString);
        Console.WriteLine(jsonObject.ToString());
        Console.WriteLine(jsonObject[0]["X1"]);
    

    Alon.

    1 person found this answer helpful.
    0 comments No comments

  2. Zhi Lv - MSFT 31,046 Reputation points Microsoft Vendor
    2021-12-24T05:32:41.487+00:00

    Hi @Julio Bello ,

    [{"X1":"x1","Y1":"y1","Z1":"z1"},{"X2":"x2","Y2":"y2","Z2":"z2"},{"X3":"x3","Y3":"y3","Z3":"z3"},...]

    From the above JSON string, we can see that each property (key-value pair, such as "X1":"x1", "X2":"x2") has a different property name or key value, in this scenario the property is not fixed so we can directly use it as the class's property.

    So, for the above JSON string, I suggest you could deserialize it uses a Dictionary<string,string>, you can refer to the following sample code:

           //required using System.Text.Json;  
    
            var values = new List<Dictionary<string, string>>()  
            {  
                  new Dictionary<string, string>()  
                    {  
                        {"X1", "x1"},{"Y1", "Y1"},{"Z1", "Z1"}  
                    },  
                      new Dictionary<string, string>()  
                    {  
                        {"X2", "x2"},{"Y2", "Y2"},{"Z2", "Z2"}  
                    }  
            };   
            var jsonstring = JsonSerializer.Serialize(values);  
            //jsonstring: [{"X1":"x1","Y1":"Y1","Z1":"Z1"},{"X2":"x2","Y2":"Y2","Z2":"Z2"}]  
            var reult1 = JsonSerializer.Deserialize<List<Dictionary<string, string>>>(jsonstring);  
    
            var test = new TestModel()  
            {  
                Item = new List<Dictionary<string, string>>()  
                {  
                    new Dictionary<string, string>()  
                    {  
                        {"X1", "x1"},{"Y1", "Y1"},{"Z1", "Z1"}  
                    },  
                      new Dictionary<string, string>()  
                    {  
                        {"X2", "x2"},{"Y2", "Y2"},{"Z2", "Z2"}  
                    }  
                }  
            };  
    
            var jsonstring2 = JsonSerializer.Serialize(test);  
            //josnstring2: {"Item":[{"X1":"x1","Y1":"Y1","Z1":"Z1"},{"X2":"x2","Y2":"Y2","Z2":"Z2"}]}  
    
            var result2 = JsonSerializer.Deserialize<TestModel>(jsonstring2);  
    

    The TestModel

    public class TestModel  
    {  
        public List<Dictionary<string, string>> Item { get; set; }  
    }  
    

    The output is like this:

    160218-1.gif

    And this sample code:

            var jsonstr = "[{\"X1\":\"x1\",\"Y1\":\"Y1\",\"Z1\":\"Z1\"},{\"X2\":\"x2\",\"Y2\":\"Y2\",\"Z2\":\"Z2\"}]";  
    
            var result3 = JsonSerializer.Deserialize<List<Dictionary<string, string>>>(jsonstr);  
    

    The result:

    160210-image.png

    After that you can find the data from the Dictionary. More detailed information about Dictionary, see Dictionary<TKey,TValue> Class


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Dillion

    0 comments No comments