将Json String转换为C#Object List

时间:2014-03-05 07:20:18

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

我想将json字符串转换为Object列表。请帮我。如果由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 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"
      }
    ]"

6 个答案:

答案 0 :(得分:63)

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

  • 转到json2csharp.com
  • 过去你的JSON in the Box。
  • Clik on Generate。
  • 您将获得对象模型的C#代码
  • 使用 NewtonJson
  • var model = JsonConvert.DeserializeObject<RootObject>(json);反序列化

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

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 :(得分:6)

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

答案 2 :(得分:1)

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

代码输出=> Output from the code

答案 3 :(得分:0)

尝试更改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; }
        }

答案 4 :(得分:0)

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

{ get; set; }

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

  

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

我希望它可以帮助那些来自VB6编程风格的人。

答案 5 :(得分:0)

请确保所有属性都是getter和setter。如果任何属性仅是getter,它将导致在键入JSON字符串时将List还原为原始数据。

请参考以下代码段: 型号:

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