許多開發人員都需要將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中文網其他相關文章!