You can use json2csharp.com to Convert your json to object model

  • Go to json2csharp.com
  • Past your JSON in the Box.
  • Clik on Generate.
  • You will get C# Code for your object model
  • Deserialize by var model = JsonConvert.DeserializeObject<RootObject>(json); using NewtonJson

Here, It will generate something like this:

public class MatrixModel
{
    public class Option
    {
        public string text { get; set; }
        public string selectedMarks { get; set; }
    }

    public class Model
    {
        public List<Option> options { get; set; }
        public int maxOptions { get; set; }
        public int minOptions { get; set; }
        public bool isAnswerRequired { get; set; }
        public string selectedOption { get; set; }
        public string answerText { get; set; }
        public bool isRangeType { get; set; }
        public string from { get; set; }
        public string to { get; set; }
        public string mins { get; set; }
        public string secs { get; set; }
    }

    public class Question
    {
        public int QuestionId { get; set; }
        public string QuestionText { get; set; }
        public int TypeId { get; set; }
        public string TypeName { get; set; }
        public Model Model { get; set; }
    }

    public class RootObject
    {
        public Question Question { get; set; }
        public string CheckType { get; set; }
        public string S1 { get; set; }
        public string S2 { get; set; }
        public string S3 { get; set; }
        public string S4 { get; set; }
        public string S5 { get; set; }
        public string S6 { get; set; }
        public string S7 { get; set; }
        public string S8 { get; set; }
        public string S9 { get; set; }
        public string S10 { get; set; }
        public string ScoreIfNoMatch { get; set; }
    }
}

Then you can deserialize as:

var model = JsonConvert.DeserializeObject<List<MatrixModel.RootObject>>(json);
Answer from L.B on Stack Overflow
🌐
GitHub
gist.github.com › alan-mushi › 19546a0e2c6bd4e059fd
Examples for the json-c tutorial. · GitHub
you just have to install libjson-c in your system. If you are using ubuntu, you can install using the following commands. sudo apt install libjson-c-dev sudo apt-get install libjson-c-dev · You only needed one of the commands....
🌐
Unity
discussions.unity.com › unity engine
How can I turn JSON String into a list of objects based on number of items. - Unity Engine - Unity Discussions
May 15, 2020 - Hey there, I am receiving a JSON string from the backend of my webserver. I managed to create a class for User profile and mapped it with the exact fields as its JSON string. Unfortunately the Items JSON string has neste…
Discussions

How can I turn JSON String into a list of objects based on number of items. - Unity Engine - Unity Discussions
Hey there, I am receiving a JSON string from the backend of my webserver. I managed to create a class for User profile and mapped it with the exact fields as its JSON string. Unfortunately the Items JSON string has nested values. How can I create an object based on the number of items in my ... More on forum.unity.com
🌐 forum.unity.com
0
May 15, 2020
Convert List<string> to JSON using C# and Newtonsoft
Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... I have a List that I would like to convert to JSON using C# and Newtonsoft. More on stackoverflow.com
🌐 stackoverflow.com
c# - Serializing a list to JSON - Stack Overflow
Note, that this option requires definition of a data contract for your class: [DataContract] public class MyObjectInJson { [DataMember] public long ObjectID {get;set;} [DataMember] public string ObjectInJson {get;set;} } ... public static string JSONSerialize(T obj) { string retVal = ... More on stackoverflow.com
🌐 stackoverflow.com
apex - JSON Array String into List - Salesforce Stack Exchange
3 Unexpected character ('a' (code 97)): expected a valid value (number, String, array, object, 'true', 'false' or 'null') at input location [1,2] 0 What's the best way to initialize a list of strings in Apex? More on salesforce.stackexchange.com
🌐 salesforce.stackexchange.com
May 6, 2022
Top answer
1 of 7
122

You can use json2csharp.com to Convert your json to object model

  • Go to json2csharp.com
  • Past your JSON in the Box.
  • Clik on Generate.
  • You will get C# Code for your object model
  • Deserialize by var model = JsonConvert.DeserializeObject<RootObject>(json); using NewtonJson

Here, It will generate something like this:

public class MatrixModel
{
    public class Option
    {
        public string text { get; set; }
        public string selectedMarks { get; set; }
    }

    public class Model
    {
        public List<Option> options { get; set; }
        public int maxOptions { get; set; }
        public int minOptions { get; set; }
        public bool isAnswerRequired { get; set; }
        public string selectedOption { get; set; }
        public string answerText { get; set; }
        public bool isRangeType { get; set; }
        public string from { get; set; }
        public string to { get; set; }
        public string mins { get; set; }
        public string secs { get; set; }
    }

    public class Question
    {
        public int QuestionId { get; set; }
        public string QuestionText { get; set; }
        public int TypeId { get; set; }
        public string TypeName { get; set; }
        public Model Model { get; set; }
    }

    public class RootObject
    {
        public Question Question { get; set; }
        public string CheckType { get; set; }
        public string S1 { get; set; }
        public string S2 { get; set; }
        public string S3 { get; set; }
        public string S4 { get; set; }
        public string S5 { get; set; }
        public string S6 { get; set; }
        public string S7 { get; set; }
        public string S8 { get; set; }
        public string S9 { get; set; }
        public string S10 { get; set; }
        public string ScoreIfNoMatch { get; set; }
    }
}

Then you can deserialize as:

var model = JsonConvert.DeserializeObject<List<MatrixModel.RootObject>>(json);
2 of 7
7
public static class Helper
{
    public static string AsJsonList<T>(List<T> tt)
    {
        return new JavaScriptSerializer().Serialize(tt);
    }
    public static string AsJson<T>(T t)
    {
        return new JavaScriptSerializer().Serialize(t);
    }
    public static List<T> AsObjectList<T>(string tt)
    {
        return new JavaScriptSerializer().Deserialize<List<T>>(tt);
    }
    public static T AsObject<T>(string t)
    {
        return new JavaScriptSerializer().Deserialize<T>(t);
    }
}
🌐
Thiago Passos
passos.com.au › converting-json-object-into-c-list
Converting JSON Objects into C# List<> - Thiago Passos
March 7, 2019 - The DataRequest would look something along these lines, but the Players property wouldn't be bound as it expects a JSON array instead of an object. public class DataRequest { public bool Status {get;set;} public string Version {get;set;} [JsonProperty("status_code")] public int StatusCode {get;set;} public TimeSpan Expires {get;set;} public List<Player> Player {get;set;} } There it comes a custom JsonConverter from Newtonsoft for the win. public class PlayersConverter : JsonConverter { // This is used when you're converting the C# List back to a JSON format public override void WriteJson(JsonW
🌐
Blogger
ebmmstech.blogspot.com › p › convert-list-object-to-json-string-in-c.html
EBM Microsoft Technology Tutorial: Convert List Object to JSON String in C#, VB.NET
By using newtonsoft.json reference in our asp.net applications we can easily convert list object to JSON string or JSON string to list object based on our requirements.
🌐
BigCodeNerd
bigcodenerd.org › blog › convert-list-objects-json-string-c
Convert List of Objects to JSON String in C | BigCodeNerd
October 1, 2024 - This guide covers struct setup, list creation, conversion function, and proper memory management for efficient data handling in C.
🌐
CSharp Academy
csharp.academy › home › how to convert json array to list in c#
How to Convert JSON Array to List in C# - CSharp Academy
November 23, 2024 - using System; using System.Collections.Generic; using Newtonsoft.Json; class Program { static void Main() { string jsonArray = @" [ { ""Id"": 1, ""Name"": ""Alice"", ""Age"": 25 }, { ""Id"": 2, ""Name"": ""Bob"", ""Age"": 30 }, { ""Id"": 3, ""Name"": ""Charlie"", ""Age"": 35 } ]"; List<Person> people = JsonConvert.DeserializeObject<List<Person>>(jsonArray); foreach (var person in people) { Console.WriteLine($"Id: {person.Id}, Name: {person.Name}, Age: {person.Age}"); } } } public class Person { public int Id { get; set; } public string Name { get; set; } public int Age { get; set; } } Id: 1, Name: Alice, Age: 25 Id: 2, Name: Bob, Age: 30 Id: 3, Name: Charlie, Age: 35 · If the JSON array contains nested objects, you’ll need to define additional classes.
Find elsewhere
🌐
C# Corner
c-sharpcorner.com › UploadFile › vendettamit › parsing-list-of-json-elements-as-list-with-json-net
Parsing List of JSON Elements as List With JSON.Net
November 11, 2020 - And so you will get a complete list of correct items and corrupted data. We'll use a JArray class from the namespace Newtonsoft.Json.Linq to parse the data as a list of arrays of objects and then we'll convert one by one each item to a typed object and add it to the list.
Top answer
1 of 9
456

If using .Net 6.0 or later;

Default to using the built in System.Text.Json parser implementation with Source Generation. Its a little more typing and compiling but, is more efficient at runtime.

The "easier to code" option below, still works but, less efficiently because it uses Reflection at runtime. The new method has some intentional, by design limitations. If you can't change your model to avoid those, the Reflection based method remains available.

e.g.

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

var aList = new List<MyObjectInJson>
{
    new(1, "1"),
    new(2, "2")
};

var json = JsonSerializer.Serialize(aList, Context.Default.ListMyObjectInJson);
Console.WriteLine(json);

return;

public record MyObjectInJson
(
    long ObjectId,
    string ObjectInJson
);

[JsonSerializable(typeof(List<MyObjectInJson>))]
internal partial class Context : JsonSerializerContext
{
}

If using .Net Core 3.0 to .Net 5.0, it is time to upgrade;

Default to using the built in System.Text.Json parser implementation.

e.g.

using System.Text.Json;

var json = JsonSerializer.Serialize(aList);

If stuck using .Net Core 2.2 or earlier;

Default to using Newtonsoft JSON.Net as your first choice JSON Parser.

e.g.

using Newtonsoft.Json;
    
var json = JsonConvert.SerializeObject(aList);

you may need to install the package first.

PM> Install-Package Newtonsoft.Json

For more details see and upvote the answer that is the source of this information.

For reference only, this was the original answer, many years ago;

// you need to reference System.Web.Extensions

using System.Web.Script.Serialization;

var jsonSerialiser = new JavaScriptSerializer();
var json = jsonSerialiser.Serialize(aList);
2 of 9
124

You can also use Json.NET. Just download it at http://james.newtonking.com/pages/json-net.aspx, extract the compressed file and add it as a reference.

Then just serialize the list (or whatever object you want) with the following:

using Newtonsoft.Json;

string json = JsonConvert.SerializeObject(listTop10);

Update: you can also add it to your project via the NuGet Package Manager (Tools --> NuGet Package Manager --> Package Manager Console):

PM> Install-Package Newtonsoft.Json

Documentation: Serializing Collections

🌐
Stack Exchange
salesforce.stackexchange.com › questions › 375426 › json-array-string-into-list
apex - JSON Array String into List - Salesforce Stack Exchange
May 6, 2022 - public class Wrapper { public String action; public String value; } Map json to wrapper and create map.
Top answer
1 of 2
2

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.

2 of 2
0

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, you can refer to the following sample code:

       //required using System.Text.Json;  

        var values = new List>()  
        {  
              new Dictionary()  
                {  
                    {"X1", "x1"},{"Y1", "Y1"},{"Z1", "Z1"}  
                },  
                  new Dictionary()  
                {  
                    {"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>>(jsonstring);  

        var test = new TestModel()  
        {  
            Item = new List>()  
            {  
                new Dictionary()  
                {  
                    {"X1", "x1"},{"Y1", "Y1"},{"Z1", "Z1"}  
                },  
                  new Dictionary()  
                {  
                    {"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(jsonstring2);  

The TestModel

public class TestModel  
{  
    public List> 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>>(jsonstr);  

The result:

After that you can find the data from the Dictionary. More detailed information about Dictionary, see Dictionary 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

🌐
Stack Overflow
stackoverflow.com › questions › 32484128 › how-to-convert-json-array-into-object-list-in-the-c-sharp
How to convert JSON array into object list in the c# - Stack Overflow
public JsonResult ReadResult() { Object1 xxx = new Object1(); Object2 aa = new Object2(); xxx.x2.Add(aa); aa = new Object2(); aa.y = "200"; aa.z = "222"; xxx.x2.Add(aa); var json = JsonConvert.SerializeObject(xxx, Formatting.None); return Json(json); } public class Object1 { public string x1 = "aaaaa"; public IList<Object2> x2 = new List<Object2>(); } public class Object2 { public string y = "100"; public string z = "10"; } ... Sign up to request clarification or add additional context in comments. ... Find the answer to your question by asking. Ask question ... See similar questions with these tags. ... I’m Jody, the Chief Product and Technology Officer at Stack Overflow.
Top answer
1 of 9
22

As others have already pointed out, the reason you are not getting the results you expect is because your JSON does not match the class structure that you are trying to deserialize into. You either need to change your JSON or change your classes. Since others have already shown how to change the JSON, I will take the opposite approach here.

To match the JSON you posted in your question, your classes should be defined like those below. Notice I've made the following changes:

  1. I added a Wrapper class corresponding to the outer object in your JSON.
  2. I changed the Values property of the ValueSet class from a List<Value> to a Dictionary<string, Value> since the values property in your JSON contains an object, not an array.
  3. I added some additional [JsonProperty] attributes to match the property names in your JSON objects.

Class definitions:

class Wrapper
{
    [JsonProperty("JsonValues")]
    public ValueSet ValueSet { get; set; }
}

class ValueSet
{
    [JsonProperty("id")]
    public string Id { get; set; }
    [JsonProperty("values")]
    public Dictionary<string, Value> Values { get; set; }
}

class Value
{
    [JsonProperty("id")]
    public string Id { get; set; }
    [JsonProperty("diaplayName")]
    public string DisplayName { get; set; }
}

You need to deserialize into the Wrapper class, not the ValueSet class. You can then get the ValueSet from the Wrapper.

var valueSet = JsonConvert.DeserializeObject<Wrapper>(jsonString).ValueSet;

Here is a working program to demonstrate:

class Program
{
    static void Main(string[] args)
    {
        string jsonString = @"
        {
            ""JsonValues"": {
                ""id"": ""MyID"",
                ""values"": {
                    ""value1"": {
                        ""id"": ""100"",
                        ""diaplayName"": ""MyValue1""
                    },
                    ""value2"": {
                        ""id"": ""200"",
                        ""diaplayName"": ""MyValue2""
                    }
                }
            }
        }";

        var valueSet = JsonConvert.DeserializeObject<Wrapper>(jsonString).ValueSet;

        Console.WriteLine("id: " + valueSet.Id);
        foreach (KeyValuePair<string, Value> kvp in valueSet.Values)
        {
            Console.WriteLine(kvp.Key + " id: " + kvp.Value.Id);
            Console.WriteLine(kvp.Key + " name: " + kvp.Value.DisplayName);
        }
    }
}

And here is the output:

id: MyID
value1 id: 100
value1 name: MyValue1
value2 id: 200
value2 name: MyValue2
2 of 9
11

http://json2csharp.com/

I found the above link incredibly helpful as it corrected my C# classes by generating them from the JSON that was actually returned.

Then I called :

JsonConvert.DeserializeObject<RootObject>(jsonString); 

and everything worked as expected.

🌐
Newtonsoft
newtonsoft.com › json › help › html › ToObjectComplex.htm
Convert JSON to Collection
This sample converts LINQ to JSON objects to .NET types using ToObjectT. ... string json = @"{ 'd': [ { 'Name': 'John Smith' }, { 'Name': 'Mike Smith' } ] }"; JObject o = JObject.Parse(json); JArray a = (JArray)o["d"]; IList<Person> person = a.ToObject<IList<Person>>(); Console.WriteLine(person[0].Name); // John Smith Console.WriteLine(person[1].Name); // Mike Smith
🌐
W3Schools
w3schools.com › js › js_json_arrays.asp
JSON Arrays
In JSON, array values must be of type string, number, object, array, boolean or null. In JavaScript, array values can be all of the above, plus any other valid JavaScript expression, including functions, dates, and undefined. ... If you want to use W3Schools services as an educational institution, ...