我有像这样的json数据
{ "John": {"StudentName": "John anow", "RegistrationNo": "xxxxx", "Grade":"B"},
"Methwe 0": {"StudentName": "Methew", "RegistrationNo": "xxxxx", "Grade":"B"},
"Johnsan 09": {"StudentName": "Johnsan anow", "RegistrationNo": "xxxxx", "Grade":"B"}
}
如何使用 C# 反序列化并转换为 JSON 数组。
下面向您展示了一种需要考虑的方法。关键是使用StudentDetails
类来定义单个学生的必要属性(以及Dictionary
- 以便它由字符串键控(例如"John"((。
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace Sample
{
public class StudentDetails
{
public string StudentName { get; set; }
public string RegistrationNo { get; set; }
public string Grade { get; set; }
}
class Program
{
static void Main(string[] args)
{
var input = @"{ ""John"": { ""StudentName"": ""John anow"", ""RegistrationNo"": ""xxxxx"", ""Grade"":""B""},
""Methwe 0"": { ""StudentName"": ""Methew"", ""RegistrationNo"": ""xxxxx"", ""Grade"":""B""},
""Johnsan 09"": { ""StudentName"": ""Johnsan anow"", ""RegistrationNo"": ""xxxxx"", ""Grade"":""B""}
}";
var output = JsonConvert.DeserializeObject<Dictionary<string, StudentDetails>>(input);
Console.ReadLine();
}
}
}