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
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 - C# treats it as key value pair foreach (var player in players) { // Finally I'm deserializing the value into an actual Player object var p = JsonConvert.DeserializeObject<Player>(player.Value.ToString()); // Also using the key as the player Id p.Id = player.Key; response.Add(p); } return response; } public override bool CanConvert(Type objectType) => objectType == typeof(List<Player>); } And to close the loop, we need to update the DataRequest to use this new converter.
Discussions

How to convert Json array to list of objects in c# - Stack Overflow
I added a Wrapper class corresponding to the outer object in your JSON. I changed the Values property of the ValueSet class from a List to a Dictionary since the values property in your JSON contains an object, not an array. More on stackoverflow.com
๐ŸŒ stackoverflow.com
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 discussions.unity.com
๐ŸŒ discussions.unity.com
0
May 15, 2020
Trying to Deserialize a JSON into a list of Objects so that they can be passed on to a view.
The error is telling you what you need to know. Did you try and understand what it is telling you? You don't say anything in your post about that. A List would look like: [{"id": "123", "tweet": "abc"}, {"id": "456", "tweet": "foobar"}] However that is CLEARLY not how your incoming data looks. It looks like this: {"data": [{"id": "123", "tweet": "abc"}, {"id": "456", "tweet": "foobar"}]} The deserializer is expecting to see a [ at the root but is bailing once it encounters a {, and telling you it needs a [ to deserialize a List. You need to create a class with a data property which is a Tweet[] (or List if you prefer) and deserialize that. Incidentally I don't think having a [ at root level is valid JSON which is probably why Twitter added the additional outer object. (Alternatively they added it to be able to add additional metadata when needed onto the root object such as error information.) More on reddit.com
๐ŸŒ r/dotnet
12
9
July 29, 2022
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
๐ŸŒ
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.
๐ŸŒ
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.
๐ŸŒ
GitHub
gist.github.com โ€บ abhith โ€บ 18af5ac6d640fc90296e
Convert Json String to C# Object List. Reference - http://stackoverflow.com/questions/22191167/convert-json-string-to-c-sharp-object-list ยท GitHub
Convert Json String to C# Object List. Reference - http://stackoverflow.com/questions/22191167/convert-json-string-to-c-sharp-object-list - Convert Json String to C# Object List.cs
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.

๐ŸŒ
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โ€ฆ
Find elsewhere
๐ŸŒ
LinkedIn
linkedin.com โ€บ pulse โ€บ c-json-array-object-mihamina-rakotomandimby
C# Json Array to Object
January 17, 2020 - As you can see in this sample, we have an array of objects. ... namespace NewCustMiddleWare { public class Article { public int userId { get; set; } public int id { get; set; } public string title { get; set; } public string body { get; set; } } ... Then we are going to fetch the web JSON Array and get them as List of objects (this is called De-serialization)
๐ŸŒ
Reddit
reddit.com โ€บ r/dotnet โ€บ trying to deserialize a json into a list of objects so that they can be passed on to a view.
r/dotnet on Reddit: Trying to Deserialize a JSON into a list of Objects so that they can be passed on to a view.
July 29, 2022 -

Let me prefix this by saying I am very new to all this so any help would be so very appreciated - i've been trying to crack this all day and it's been a real struggle. Im making this webapp in ASP.NET core btw. So I've managed to call the twitter api and return back some tweets as JSON depending on a search query. I am then trying to deserialize these into C# objects (using the Tweet class). I then want to pass these objects through as a list to the view for it to render them all out But I just can't seem to get it to work.

I am trying to put desrialize the JSON that comes back into Tweet objects and put them into a ViewModel and then pass the viewmodel to the view. This is what comes back from the API call so I know thats working ok. This is what the Tweet class looks like. The SocialMediaType property is a class in itself, and just has two properties on it which are an Id and name which are given default values as they will always be the same. The error page
๐ŸŒ
Json2CSharp
json2csharp.com
Convert JSON to C# Classes Online - Json2CSharp Toolkit
JSON: { 'test' : null} C#: [JsonProperty("test", NullValueHandling = NullValueHandling.Ignore)] public object test { get; set; } ... Creates readonly classes that are instantiated using the class constructor. JSON: { 'test' : 'test'} C#: public Root( string test) { this.test = test; } public string test { get; } ... Creates readonly lists for collection types.
๐ŸŒ
Tutorial Teacher
tutorialsteacher.com โ€บ articles โ€บ convert-json-string-to-object-in-csharp
Parse JSON string to Class Object in C#
Many times the JSON string contains an array to store multiple data. This can be converted to an array or list of objects in C#. The following example shows how to parse JSON array to C# list collection.
๐ŸŒ
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 - Create a C# class that matches the structure of the JSON objects: public class Person { public int Id { get; set; } public string Name { get; set; } public int Age { get; set; } } Use the JsonConvert.DeserializeObject method to parse the JSON array and convert it into a List<Person>.
๐ŸŒ
Reddit
reddit.com โ€บ r/csharp โ€บ [help] json array to list
r/csharp on Reddit: [Help] JSON Array to List
November 4, 2019 -

Hi all,

I'm playing around with JSON and I have a JSON array that I'd like to add into a Listbox. I've only ever used a single JSON before and I'm not sure how to do it with a JSON Array using NewtonSoft.

{
    "1": {
        "id": "628190",
        "entrant": "ENTRANT NAME",
        "recipient": "RECIPIENT NAME",
        "task": "Task Description"
    }
    "2": {
        "id": "628191",
        "entrant": "ENTRANT NAME",
        "recipient": "RECIPIENT NAME",
        "task": "Task Description"
    }
    "3": {
        "id": "628192",
        "entrant": "ENTRANT NAME",
        "recipient": "RECIPIENT NAME",
        "task": "Task Description"
    }
}

I know I'm missing a foreach or something like that. In the past I've only done something like this:

{
    "description": "Some description",
    "reason": "Some reason"
}

and I've just used this

Details detail = JsonConvert.DeserializeObject<Details>(webResult1);
Top answer
1 of 2
5

Here's how to think about deserializing JSON.

There are two paths, and one is easier. The easier is to make a C# object graph that looks like the JSON object, then deserialize to it. The harder is to use the token parser or types like JObject to do the same thing with a little more effort. The harder paths are better if the JSON is really "weird" and requires special effort to get into sensible C# objects.

This isn't quite bad enough to need to use JArray. Obviously you can't make a C# object with a property named "1", "2", "3", and so on, but there's another way to go about this. Any JSON object is effectively a Dictionary<string, object>, so our first decision can be that this is our outer object.

The inner objects of this dictionary do have a well-defined type. They have four properties that are strings, though maybe for your logic "id" will be a number. So we can make an object to represent this and have a more specific Dictionary.

So I'd start with:

public class JsonTask
{
    public string Id { get; set; }
    public string Entrant { get; set; }
    public string Recipient { get; set; }
    public string Task { get; set; }
}

Then the code to get the dictionary is:

var dict = JsonConvert.DeserializeObject<Dictionary<string, JsonTask>>(json);

From there, getting an array could be:

var asArray = dict.Values.ToArray();

If order is super important, you might have to do something more complex. If you know all the properties are always sequential integers, a for loop over Keys is good enough. If they might not be ordered, you might try converting Keys to an array, sorting it, then using each key to fetch each value.

I don't think the other comment about deserializing to a list will work, generally you can only deserialize JSON arrays to lists, and this is more of an object being used as a dictionary.

2 of 2
2

That... is not an array, is it? An array is using [], you just have an object with properties 1, 2, and 3. I don't think that'd even work.

To deserialize into a list, you'd do something like JsonConvert.DeserializeObject<List<Details>>(webResult1);

๐ŸŒ
Newtonsoft
newtonsoft.com โ€บ json โ€บ help โ€บ html โ€บ ToObjectComplex.htm
Convert JSON to Collection
This sample converts LINQ to JSON objects to .NET types using M:Newtonsoft.Json.Linq.JToken.ToObject``1.
๐ŸŒ
Aspdotnet-suresh
aspdotnet-suresh.com โ€บ 2017 โ€บ 02 โ€บ convert-list-object-to-json-string-in-csharp-vbnet.html
Convert List Object to JSON String in C#, VB.NET
how to convert list object to JSON string in asp.net using c#, vb.net with example or how to convert JSON string to generic list in c#, vb.net with example or convert list of objects to JSON string in asp.net using c#, vb.net with example. 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.
๐ŸŒ
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.