Sta*_*ker 0 c# parsing json json.net
我目前正在使用beta API(http://developer.riotgames.com/api/methods),它为所有公开的方法返回JSON.到目前为止,我已经能够使用JSON.NET反序列化所有这些返回值.但是,今天我消耗了他们的一个函数,它返回一个有效但在我看来不正确的JSON.
你可能想知道,为什么不在beta论坛上问它?我有,但到目前为止我还没有得到答案,总的来说这引起了我的兴趣.
JSON返回的片段:
"1001": {
"name": "Boots of Speed",
"plaintext": "Slightly increases Movement Speed",
"group": "BootsNormal",
"description": "<...
}
Run Code Online (Sandbox Code Playgroud)
我对这种结构的问题是ID被用作没有标识符的"组".如果有的话,我可以很好地使用它
"ItemID" : "1001"
Run Code Online (Sandbox Code Playgroud)
但它没有那个.我不介意手动解析它,但我首先想知道这个JSON是否正确(不仅仅是有效的).
您是否同意这不是一种创建包含元素列表的JSON块的简洁方法,或者我在这里遗漏了什么?到目前为止,我还没有看到有关此API的beta论坛的任何评论,所以我真的很想知道为什么.
编辑"有效"vs"正确/可用":我知道这是一个有效的JSON语句.我在质疑这是否可用于JSON.NET.
我有以下类定义(带有两个子类):
public class JSONItem
{
[JsonProperty("tags")]
public string[] Tags { get; set; }
[JsonProperty("plaintext")]
public string Plaintext { get; set; }
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("into")]
public string[] Into { get; set; }
[JsonProperty("image")]
public JSONItemImage Image { get; set; }
[JsonProperty("colloq")]
public string Colloq { get; set; }
[JsonProperty("gold")]
public JSONItemGold Gold { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
将上述JSON块提供给JSONConvert.DeserializeObject(json)时,会抛出错误,因为JSONItem中未提及"1001".你如何处理这个,以便你可以使用JSON.NET?
像这样的类将无法工作,因为您没有名称来提供属性:
public class JSONItemWrapper
{
[JsonProperty("")]
public string ID { get; set; }
[JsonProperty("")]
public JSONItem MyProperty { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
编辑:"与其他方法一致"其他方法返回每个属性在{}内并具有标识符的块.最近添加的函数具有"{}之外的主键"样式.
它是一个有效的json,您可以使用类似Dictionary<string, SomeObject>反序列化您的json.
string json = @"{
""1001"": {
""name"": ""Boots of Speed"",
""plaintext"": ""Slightly increases Movement Speed"",
""group"": ""BootsNormal"",
""description"": ""desc...""
}
}";
var dict = JsonConvert.DeserializeObject<Dictionary<string, MyObject>>(json);
Run Code Online (Sandbox Code Playgroud)
并且稍后通过其键访问项目也可以很快.
public class MyObject
{
public string name { get; set; }
public string plaintext { get; set; }
public string group { get; set; }
public string description { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
102 次 |
| 最近记录: |