【发布时间】:2016-10-01 00:00:27
【问题描述】:
我正在尝试反序列化描述以下内容的 json:
Item 类型的对象列表,每个 Item 包含一些属性以及 Effect 类型的对象的列表“配方”,其中包含它们自己的三个属性(动作、值和目标)。
当我使用 'JsonConvert.SerializeObject' 序列化我的列表时,我得到以下 json:
[
{
"name": "WOOD",
"yield": 1.0,
"recipe": [
{
"action": "ADD",
"value": 1.0,
"target": "WOOD"
}
],
"count": 0.0,
"numWorkers": 0,
"id": 1
},
{
"name": "CLAY",
"yield": 2.0,
"recipe": [
{
"action": "ADD",
"value": 2.0,
"target": "CLAY"
}
],
"count": 0.0,
"numWorkers": 0,
"id": 2
},
{
"name": "SPEAR",
"yield": 0.5,
"recipe": [
{
"action": "ADD",
"value": 0.5,
"target": "SPEAR"
},
{
"action": "SUB",
"value": 1.0,
"target": "WOOD"
},
{
"action": "SUB",
"value": 5.0,
"target": "CLAY"
}
],
"count": 0.0,
"numWorkers": 0,
"id": 3
},
{
"name": "STICK",
"yield": 4.0,
"recipe": [
{
"action": "ADD",
"value": 4.0,
"target": "STICK"
},
{
"action": "SUB",
"value": 1.0,
"target": "WOOD"
}
],
"count": 0.0,
"numWorkers": 0,
"id": 4
}
]
但是当我尝试使用“Items = JsonConvert.DeserializeObject<List<Item>>(jsonstring);”反序列化时,我收到此错误:A first chance exception of type 'System.NullReferenceException' occurred in Newtonsoft.Json.dll 并且我的“项目”列表为空。
当我使用 json2csharp 生成 c# 时,我得到以下信息:
public class Recipe
{
public string action { get; set; }
public double value { get; set; }
public string target { get; set; }
}
public class RootObject
{
public string name { get; set; }
public double yield { get; set; }
public List<Recipe> recipe { get; set; }
public double count { get; set; }
public int numWorkers { get; set; }
public int id { get; set; }
}
它认为我的 Item 对象是“RootObject”,它给了我一个“Recipe”对象,而不是“recipe”列表中的“Effect”对象列表
以下是我的游戏和类的一些代码,您可以看到我正在处理的内容:
public List<Item> Items;
private void Game_Load(object sender, EventArgs e)
{
Items = JsonConvert.DeserializeObject<List<Item>>(jsonstring);
}
public class Item
{
public string name;
public double yield;
public List<Effect> recipe = new List<Effect>();
public double count;
public int numWorkers;
public int id;
public Item()
{
name = "";
//configureItem();
}
public Item(string nm)
{
name = nm.ToUpper();
//configureItem();
}
public List<Effect> getRecipe() {
return recipe;
}
}
public class Effect
{
public string action;
public double value;
public string target;
public Effect(string act, double val, string tar)
{
action = act.ToUpper();
value = val;
target = tar.ToUpper();
}
}
我的课程中的所有变量都需要{ get; set; } 吗?我之前尝试添加它,但它似乎导致我的 VS 在调试期间跳过行以及各种其他奇怪的东西。还是只是 Json 格式问题?任何帮助将不胜感激,我已经浏览了整个网站和谷歌,我在这里扯掉了我的头发。
【问题讨论】:
标签: c# json list json.net deserialization