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:
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:
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