将JSON反序列化为C#对象

24

你好,我急需帮助。我有一个JSON文件,其中包含一组JSON对象。我无法弄清如何将其反序列化为此对象列表。

我的JSON文件格式如下 - 它有数千行,这只是一个样本:

[{
"Rk": 1,
"Gcar": 467,
"Gtm": 1,
"Date": "Apr 6",
"Tm": "CLE",
"Where": "@",
"Opp": "HOU",
"Rslt": "L0-2",
"Inngs": "CG",
"PA": 4,
"AB": 4,
"R": 0,
"H": 0,
"Doubles": 0,
"Triples": 0,
"HR": 0,
"RBI": 0,
"BB": 0,
"IBB": 0,
"SO": 0,
"HBP": 0,
"SH": 0,
"SF": 0,
"ROE": 0,
"GDP": 0,
"SB": 0,
"CS": 0,
"BA": 0,
"OBP": 0,
"SLG": 0,
"OPS": 0,
"BOP": 2,
"aLI": 0.93,
"WPA": -0.093,
"RE24": -0.64,
"DFSDK": 0,
"DFSFD": -1,
"Pos": "Doubles"
},

{
"Rk": 2,
"Gcar": 468,
"Gtm": 2,
"Date": "Apr 8",
"Tm": "CLE",
"Where": "@",
"Opp": "HOU",
"Rslt": "W2-0",
"Inngs": "CG",
"PA": 4,
"AB": 4,
"R": 0,
"H": 2,
"Doubles": 0,
"Triples": 0,
"HR": 0,
"RBI": 0,
"BB": 0,
"IBB": 0,
"SO": 0,
"HBP": 0,
"SH": 0,
"SF": 0,
"ROE": 0,
"GDP": 0,
"SB": 0,
"CS": 0,
"BA": 0.25,
"OBP": 0.25,
"SLG": 0.25,
"OPS": 0.5,
"BOP": 3,
"aLI": 0.71,
"WPA": -0.008,
"RE24": -0.2,
"DFSDK": 6,
"DFSFD": 1.5,
"Pos": "Doubles"
}
]

这个文件中有142个这样的对象。我试图反序列化对象,但没有成功。现在我准备从头开始,并且只是想寻求一些方向,以便将这些数据转换为可用的对象。

谢谢。


你是否遇到了错误,或者出了什么具体的问题? - lc.
每当我尝试将它转换为JObject时,它会说无法识别其为json格式。因此,我已经创建了一个类,其中包含来自Json对象的所有字段,并且我想知道将数据传递到这种类型的列表中的最佳方法是什么? - siegs
这是一个 JsonArray 吗?你使用的是哪个库? - Ophitect
字符串 jsonString = reader.ReadToEnd(); JArray myObj = (JArray)JsonConvert.DeserializeObject(jsonString); - siegs
我创建了一个类,其中包含类型为<player>的列表,该列表包含来自我的JSON数据的所有字段。如何将JArray放入该列表中? - siegs
显示剩余3条评论
5个回答

63
你可以使用 Visual Studio 2013、2015 创建你的模型类,从 JSON 中生成它们。我尝试过并成功解析了 JSON。 要使用这个功能,你需要将 JSON/XML 复制到剪贴板中,把光标放在 .cs 文件里然后使用选项编辑 > 粘贴特殊 > 粘贴 JSON 作为类

Paste Special JSON as classes

查看生成的代码:

public class Rootobject
{
    public Class1[] Property1 { get; set; }
}

public class Class1
{
    public int Rk { get; set; }
    public int Gcar { get; set; }
    public int Gtm { get; set; }
    public string Date { get; set; }
    public string Tm { get; set; }
    public string Where { get; set; }
    public string Opp { get; set; }
    public string Rslt { get; set; }
    public string Inngs { get; set; }
    public int PA { get; set; }
    public int AB { get; set; }
    public int R { get; set; }
    public int H { get; set; }
    public int Doubles { get; set; }
    public int Triples { get; set; }
    public int HR { get; set; }
    public int RBI { get; set; }
    public int BB { get; set; }
    public int IBB { get; set; }
    public int SO { get; set; }
    public int HBP { get; set; }
    public int SH { get; set; }
    public int SF { get; set; }
    public int ROE { get; set; }
    public int GDP { get; set; }
    public int SB { get; set; }
    public int CS { get; set; }
    public float BA { get; set; }
    public float OBP { get; set; }
    public float SLG { get; set; }
    public float OPS { get; set; }
    public int BOP { get; set; }
    public float aLI { get; set; }
    public float WPA { get; set; }
    public float RE24 { get; set; }
    public int DFSDK { get; set; }
    public float DFSFD { get; set; }
    public string Pos { get; set; }
}

使用Visual Studio创建的此对象进行JSON反序列化时,可以使用Newtonsoft.Json。您可以使用以下命令通过nuget安装:

在运行时将JSON反序列化为此对象所需的是Newtonsoft.Json。您可以使用以下命令通过nuget安装:

Install-Package Newtonsoft.Json

现在,您可以使用静态类 JsonCovert 中的通用方法 DeserializeObject 对其进行反序列化,就像这样:

现在,您可以使用静态类JsconCovert中的通用方法DeserializedObject对其进行反序列化,就像这样:

Rootobject object = JsonConvert.DeserializeObject<Rootobject>(jsonString); 

太棒了!有很多好答案,但这个真的改变了我的生活! - siegs
不错的提示。你让我的一天变得更好了。 - Shakeer Hussain
1
太好了..!! 感谢提供新的将 JSON 转换为 C# 对象的方法。真是太棒了。 - Vishvanathsinh Solanki
幸运的是我看到了这个,我通常都是手动创建它们。 - WtFudgE
太简单了 - 非常感谢你!! - undefined

7

使用Newtonsoft.JSON很容易实现,文档中有一页覆盖了如何反序列化对象

摘自文档页面:

public class Account
{
    public string Email { get; set; }
    public bool Active { get; set; }
    public DateTime CreatedDate { get; set; }
    public IList<string> Roles { get; set; }
}

// code to deserialize from JSON string to a typed object
string json = @"{
    'Email': 'james@example.com',
    'Active': true,
    'CreatedDate': '2013-01-20T00:00:00Z',
    'Roles': [
        'User',
        'Admin'
    ]
";

Account account = JsonConvert.DeserializeObject<Account>(json);

Console.WriteLine(account.Email);
// james@example.com

3
Newtonsoft 提供了一种方法来做到这一点。
CustomClass myClassWithCollection = JsonConvert.DeserializeObject<CustomClass>(jsonString);

0
using(StreamReader reader = new StreamReader(@"path"))
{
     string jsonString = reader.ReadToEnd();
     JArray myObj = (JArray)JsonConvert.DeserializeObject(jsonString);

     var player = new Player();
     player.statsBase = myObj.ToObject<List<StatsBase>>();
}

这就是我最终完成它的方式。我不确定上面的答案是否适用于同一文件中的多个JSON对象。


试试我的答案,这是更好的方法。 - Igor Quirino

0

尝试使用Newtonsoft.Json库。

在您的项目中添加https://www.nuget.org/packages/Newtonsoft.Json/7.0.1

这是我的解决方案链接:https://dotnetfiddle.net/eqJXTy

然后:

List<Dictionary<string, string>> obj =
    Newtonsoft.Json.JsonConvert.
        DeserializeObject<List<Dictionary<string, string>>>(jsonString);

foreach(Dictionary<string, string> lst in obj)
{
    Console.WriteLine("--NewObject--");
    Console.WriteLine(string.Format("Rk: {0} Gcar: {1}", lst["Rk"], lst["Gcar"]));
    foreach(KeyValuePair<string, string> item in lst)
    {
        Console.WriteLine(string.Format("Key: {0} Value: {1}", item.Key, item.Value));
    }
}

很高兴能够帮助您!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接