Convert Json String to C# Object List

268,149

Solution 1

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

Solution 2

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

Solution 3

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

Solution 4

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

Share:
268,149

Related videos on Youtube

Pratik Bhoir
Author by

Pratik Bhoir

Hello

Updated on July 09, 2022

Comments

  • Pratik Bhoir
    Pratik Bhoir almost 2 years

    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"
          }
        ]"
    
  • Junaid
    Junaid almost 9 years
    Simply awesome . Thanks for help
  • Ariel
    Ariel almost 9 years
    +1 for the website, great help ! One thing, i'm getting an error and i can't figure out where is the problem: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type System.Collections.Generic.List 1[Library.BL.Unidade+RootObject] because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly. To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer. CODE
  • L.B
    L.B almost 9 years
    @Terkhos Most probably your json is an array, not a single object. Try JsonConvert.DeserializeObject<List<RootObject>>(json);
  • Nithin Veer Reddy Kankanti
    Nithin Veer Reddy Kankanti over 8 years
    Simply Awesome Great website
  • Rapsoulis
    Rapsoulis about 7 years
    How would I be able access the value of "selectedMarks"?
  • lachs
    lachs about 4 years
    Link is broken :(