[c#] Convert Json String to C# Object List

I want to convert a json string to a Object list. Please help me. it would be more helpful if done by NewtonJson.

I tried, but its not working. I dont want all the values of that json. just which are mentioned in the MatrixModel

This is a Object

public class MatrixModel
{
    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 int ScoreIfNoMatch { get; set; }
}

This is the Json String

    "[
      {
        "Question": {
          "QuestionId": 49,
          "QuestionText": "Whats your name?",
          "TypeId": 1,
          "TypeName": "MCQ",
          "Model": {
            "options": [
              {
                "text": "Rahul",
                "selectedMarks": "0"
              },
              {
                "text": "Pratik",
                "selectedMarks": "9"
              },
              {
                "text": "Rohit",
                "selectedMarks": "0"
              }
            ],
            "maxOptions": 10,
            "minOptions": 0,
            "isAnswerRequired": true,
            "selectedOption": "1",
            "answerText": "",
            "isRangeType": false,
            "from": "",
            "to": "",
            "mins": "02",
            "secs": "04"
          }
        },
        "CheckType": "",
        "S1": "",
        "S2": "",
        "S3": "",
        "S4": "",
        "S5": "",
        "S6": "",
        "S7": "",
        "S8": "",
        "S9": "Pratik",
        "S10": "",
        "ScoreIfNoMatch": "2"
      },
      {
        "Question": {
          "QuestionId": 51,
          "QuestionText": "Are you smart?",
          "TypeId": 3,
          "TypeName": "True-False",
          "Model": {
            "options": [
              {
                "text": "True",
                "selectedMarks": "7"
              },
              {
                "text": "False",
                "selectedMarks": "0"
              }
            ],
            "maxOptions": 10,
            "minOptions": 0,
            "isAnswerRequired": false,
            "selectedOption": "3",
            "answerText": "",
            "isRangeType": false,
            "from": "",
            "to": "",
            "mins": "01",
            "secs": "04"
          }
        },
        "CheckType": "",
        "S1": "",
        "S2": "",
        "S3": "",
        "S4": "",
        "S5": "",
        "S6": "",
        "S7": "True",
        "S8": "",
        "S9": "",
        "S10": "",
        "ScoreIfNoMatch": "2"
      }
    ]"

This question is related to c# javascript asp.net-mvc json json.net

The answer is


using dynamic variable in C# is the simplest.

Newtonsoft.Json.Linq has class JValue that can be used. Below is a sample code which displays Question id and text from the JSON string you have.

        string jsonString = "[{\"Question\":{\"QuestionId\":49,\"QuestionText\":\"Whats your name?\",\"TypeId\":1,\"TypeName\":\"MCQ\",\"Model\":{\"options\":[{\"text\":\"Rahul\",\"selectedMarks\":\"0\"},{\"text\":\"Pratik\",\"selectedMarks\":\"9\"},{\"text\":\"Rohit\",\"selectedMarks\":\"0\"}],\"maxOptions\":10,\"minOptions\":0,\"isAnswerRequired\":true,\"selectedOption\":\"1\",\"answerText\":\"\",\"isRangeType\":false,\"from\":\"\",\"to\":\"\",\"mins\":\"02\",\"secs\":\"04\"}},\"CheckType\":\"\",\"S1\":\"\",\"S2\":\"\",\"S3\":\"\",\"S4\":\"\",\"S5\":\"\",\"S6\":\"\",\"S7\":\"\",\"S8\":\"\",\"S9\":\"Pratik\",\"S10\":\"\",\"ScoreIfNoMatch\":\"2\"},{\"Question\":{\"QuestionId\":51,\"QuestionText\":\"Are you smart?\",\"TypeId\":3,\"TypeName\":\"True-False\",\"Model\":{\"options\":[{\"text\":\"True\",\"selectedMarks\":\"7\"},{\"text\":\"False\",\"selectedMarks\":\"0\"}],\"maxOptions\":10,\"minOptions\":0,\"isAnswerRequired\":false,\"selectedOption\":\"3\",\"answerText\":\"\",\"isRangeType\":false,\"from\":\"\",\"to\":\"\",\"mins\":\"01\",\"secs\":\"04\"}},\"CheckType\":\"\",\"S1\":\"\",\"S2\":\"\",\"S3\":\"\",\"S4\":\"\",\"S5\":\"\",\"S6\":\"\",\"S7\":\"True\",\"S8\":\"\",\"S9\":\"\",\"S10\":\"\",\"ScoreIfNoMatch\":\"2\"}]";
        dynamic myObject = JValue.Parse(jsonString);
        foreach (dynamic questions in myObject)
        {
            Console.WriteLine(questions.Question.QuestionId + "." + questions.Question.QuestionText.ToString());
        }
        Console.Read();

Output from the code => Output from the code


The variables/parameters within the class definition requires { get; set; } I was using like a variable declaration (stupid of me, because it was working for other scenarios) without

{ get; set; }

Because of which, whatever I send from the JavaScript, it was not being received in the Action method. It was always getting null or empty model.

Once the {get; set;} is added, it worked like charm.

I hope it helps someone who is coming from VB6 style of programming line.


Try to change type of ScoreIfNoMatch, like this:

   public class MatrixModel
        {
            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; }
            // the type should be string
            public string ScoreIfNoMatch { get; set; }
        }

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);
    }
}

Please make sure that all properties are both the getter and setter. In case, any property is getter only, it will cause the reverting the List to original data as the JSON string is typed.

Please refer to the following code snippet for the same: Model:

 public class Person
{
    public int ID { get; set; }
    // following 2 lines are cause of error
    //public string Name { get { return string.Format("{0} {1}", First, Last); } }
    //public string Country { get { return Countries[CountryID]; } }
    public int CountryID { get; set; }
    public bool Active { get; set; }
    public string First { get; set; }
    public string Last { get; set; }
    public DateTime Hired { get; set; }
}
public class ModelObj
    {
        public string Str { get; set; }
        public List<Person> Persons { get; set; }
    }

Controller:

 [HttpPost]
    public ActionResult Index(FormCollection collection)
    {
        var data = new ModelObj();
        data.Str = (string)collection.GetValue("Str").ConvertTo(typeof(string));
        var personsString = (string)collection.GetValue("Persons").ConvertTo(typeof(string));
        using (var textReader = new StringReader(personsString))
        {
            using (var reader = new JsonTextReader(textReader))
            {
                data.Persons = new JsonSerializer().Deserialize(reader, typeof(List<Person>)) as List<Person>; 
            }
        }

        return View(data);
    }

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to asp.net-mvc

Using Lato fonts in my css (@font-face) Better solution without exluding fields from Binding Vue.js get selected option on @change You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to send json data in POST request using C# VS 2017 Metadata file '.dll could not be found The default XML namespace of the project must be the MSBuild XML namespace How to create roles in ASP.NET Core and assign them to users? The model item passed into the dictionary is of type .. but this dictionary requires a model item of type How to use npm with ASP.NET Core

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to json.net

Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path Return JsonResult from web api without its properties Checking for empty or null JToken in a JObject Send JSON via POST in C# and Receive the JSON returned? Unexpected character encountered while parsing value JSON.net: how to deserialize without using the default constructor? Could not load file or assembly 'Newtonsoft.Json' or one of its dependencies. Manifest definition does not match the assembly reference Cannot deserialize the JSON array (e.g. [1,2,3]) into type ' ' because type requires JSON object (e.g. {"name":"value"}) to deserialize correctly Could not load file or assembly 'Newtonsoft.Json, Version=4.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' Convert Json String to C# Object List