【问题标题】:Convert Json String to C# Object List将 Json 字符串转换为 C# 对象列表
【发布时间】:2014-04-07 02:56:00
【问题描述】:

我想将一个 json 字符串转换为一个对象列表。请帮我。如果由NewtonJson完成会更有帮助。

我试过了,但它不起作用。我不想要那个json的所有值。正是在MatrixModel中提到的

这是一个对象

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

这是 Json 字符串

    "[
      {
        "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"
      }
    ]"

【问题讨论】:

标签: c# javascript asp.net-mvc json json.net


【解决方案1】:

您可以使用json2csharp.com 将您的 json 转换为对象模型

  • 转到json2csharp.com
  • 在 Box 中传递您的 JSON。
  • 点击生成。
  • 您将获得对象模型的 C# 代码
  • var model = JsonConvert.DeserializeObject<RootObject>(json); 使用 NewtonJson 反序列化

在这里,它会生成如下内容:

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

那么你可以反序列化为:

var model = JsonConvert.DeserializeObject<List<MatrixModel.RootObject>>(json);

【讨论】:

  • 简直太棒了。感谢您的帮助
  • 网站+1,非常有帮助!一件事,我遇到了一个错误,我不知道问题出在哪里: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
  • @Terkhos 您的 json 很可能是一个数组,而不是单个对象。试试JsonConvert.DeserializeObject&lt;List&lt;RootObject&gt;&gt;(json);
  • 简直太棒了,很棒的网站
  • 我怎样才能访问“selectedMarks”的值?
【解决方案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);
    }
}

【讨论】:

    【解决方案3】:

    请确保所有属性都是 getter 和 setter。如果任何属性仅是 getter,则会导致在键入 JSON 字符串时将列表恢复为原始数据。

    请参考以下代码sn-p: 型号:

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

    控制器:

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

    【讨论】:

      【解决方案4】:

      在C#中使用动态变量是最简单的。

      Newtonsoft.Json.Linq 具有可以使用的 JValue 类。下面是一个示例代码,它显示您拥有的 JSON 字符串中的问题 ID 和文本。

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

      代码输出 =>

      【讨论】:

        【解决方案5】:

        尝试更改 ScoreIfNoMatch 的类型,如下所示:

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

        【讨论】:

          【解决方案6】:

          class 定义中的变量/参数需要{ get; set; } 我像变量声明一样使用(我很愚蠢,因为它适用于其他场景)而没有

          { get; set; }
          

          因此,无论我从 JavaScript 发送什么,Action 方法都没有收到它。它总是得到 null 或空模型。

          一旦{get; set;} 被添加,它就像魅力一样。

          我希望它对那些来自 VB6 风格的编程行的人有所帮助。

          【讨论】:

            猜你喜欢
            • 2018-05-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2022-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多