c# - 如何使用 POCO 类反序列化包含数字的 JSON 属性?
问题描述
我在Unity引擎中使用JSONUtility练习JSON反序列化。我在stackoverflow(Link)的帮助下使用POCO类解决了一些示例。我已经解决了以下JSON。使用 POCO 类中的确切名称进行链接。但是当 JSON 属性包含如下整数时。
{
"1": {
"Armor": 1,
"Strenght": 1
},
"0": {
"Armor": 1,
"Mana": 2,
"Strenght": 1,
"Health": 1,
"Power": 1
}
}
以类似的方式解决没有成功。根据我得到的反馈,我必须使用字典。
IEnumerator GetExampleValues()
{
string URLss = "http://www.json-generator.com/api/json/get/bOQGnptixu?indent=2";
WWW readjson = new WWW(URLss);
yield return readjson;
Debug.Log("ReadJSON"+readjson.text);
}
下面是我的 POCO 课程
using System.Collections.Generic;
[System.Serializable]
public class Exampleget
{
public int Power;
public int Mana;
public int Strenght;
public int Armor;
public int Health;
}
public class GetNumbers
{
public List<Exampleget> onevalues;
}
解决方案
解决此问题的一种方法是使用 JsonExtensionData 属性
public class Exampleget
{
public int Power;
public int Mana;
public int Strenght;
public int Armor;
public int Health;
}
public class GetNumbers
{
[JsonExtensionData]
public Dictionary<string,dynamic> Values;
}
有了班级,现在你可以,
var str = @"{
'1': {
'Armor': 1,
'Strenght': 1
},
'0': {
'Armor': 1,
'Mana': 2,
'Strenght': 1,
'Health': 1,
'Power': 1
}
}";
var result = JsonConvert.DeserializeObject<GetNumbers>(str);
foreach(var item in result.Values)
{
Console.WriteLine($"For Key {item.Key},Power = {item.Value.Power}, Mana = {item.Value.Mana}, Armor = {item.Value.Armor}, Health = {item.Value.Health}");
}
输出
For Key 1,Power = , Mana = , Armor = 1, Health =
For Key 0,Power = 1, Mana = 2, Armor = 1, Health = 1
更新
如果您想使用 DictionaryDictionary<string,Exampleget>
而不是使用动态,那么您可以使用转换为 Exampleget 的附加属性。但这是以额外的序列化/反序列化为代价的,因此除非您有充分的理由坚持下去,否则不建议这样做。
public class GetNumbers
{
[JsonExtensionData]
public Dictionary<string,object> Values;
[JsonIgnore]
public Dictionary<string,Exampleget> ExamplegetDictionary=> Values.Select(x=>new KeyValuePair<string,Exampleget>(x.Key, ((object)x.Value).Cast<Exampleget>()))
.ToDictionary(x=>x.Key,y=>y.Value);
}
public static class Extension
{
public static T Cast<T>(this object value)
{
var jsonData = JsonConvert.SerializeObject(value);
return JsonConvert.DeserializeObject<T>(jsonData);
}
}
推荐阅读
- haskell - 是否可以定义这样的 malloc 和 free 以使其数据由 GHC 运行时管理?
- mysql - 我应该将列一一添加到mysql db而不是在一个语句中吗
- r - 根据投票百分比同时移动所有几何条
- html - 显示:表头组在打印时无法在 chorme 中工作
- git - Git 日志 - 显示合并请求 ID
- python - Pandas 按多列分组并从非分组列中选择非空最后一个值
- azure - MS GRAPH API - 创建订阅 - 403 错误 - 调用者无权访问资源
- java - Spring Boot 2.3.x - 如何在自定义@RestController 中应用投影?
- javascript - 如何将数据传递给 ajax 以进行快速 api 调用
- r - 归一化数据的低方差过滤器