许多开发人员都需要将 JSON 字符串转换为 C# 对象以进行数据操作和处理。借助 JSON.NET(一个用于在 .NET 应用程序中处理 JSON 数据的流行库)可以使此任务变得更容易。
假设您有一个包含对象数组的 JSON 字符串。该数组中的对象拥有与定义的 C# 类(称为 MatrixModel)的属性相对应的特定属性。要将此 JSON 字符串转换为 MatrixModel 对象列表,您可以按照以下步骤操作:
var matrixModelList = JsonConvert.DeserializeObject<List<MatrixModel>>(json);
示例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" } ]"
反序列化对象示例:
var model = JsonConvert.DeserializeObject<List<MatrixModel.RootObject>>(json);
现在,您可以轻松使用反序列化的 MatrixModel 列表,访问和操作数据根据您的 C# 应用程序的需要。
以上是如何使用 JSON.NET 将 JSON 字符串转换为 C# 对象列表?的详细内容。更多信息请关注PHP中文网其他相关文章!