[英]How to deserialize a JSON Properties containing numbers using POCO class?
我在Unity引擎中使用JSONUtility練習JSON反序列化。當屬性為string時,通過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
更新
如果您希望將Dictionary作為Dictionary<string,Exampleget>
而不是使用dynamic,則可以利用附加屬性將其轉換為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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.