【发布时间】:2011-11-23 21:41:42
【问题描述】:
我正在尝试使用 JSON.Net 将 JSON 对象反序列化为 C# 对象。
我要创建的对象是MonthlyPerformance,其中包含Type 列表,其中包含Categories 列表,而Categories 列表又包含Funds 列表。它们被定义为:
public class MonthlyPerformance
{
public List<Type> Types { get; set; }
}
public class Type
{
public int Id { get; set; }
public string CountryId { get; set; }
public string Name { get; set; }
public List<Category> Categories { get; set; }
public Type()
{
}
}
public class Category
{
public int Id { get; set; }
public string CountryId { get; set; }
public string Name { get; set; }
public List<ConfigurationFund> Funds { get; set; }
public Category()
{
}
}
public class Fund
{
public int Id { get; set; }
public string CountryId { get; set; }
public string Name { get; set; }
public Fund()
{
}
}
我认为以下内容会做到这一点,但事实并非如此。它只是创建了一个 Type 对象的实例,所有内容都为空:
var file = File.ReadAllText(filePath);
var types = JsonConvert.DeserializeObject<Type>(file);
这是我正在使用的 JSON:
{
"MonthlyPerformance": {
"Type": [
{
"id": "65",
"countryId": "IE",
"name": "Irish Domestic Funds (Gross)",
"Category": [
{
"id": "25003334",
"countryId": "IE",
"name": "UK Equity",
"ConfigurationFund": [
{
"id": "25000301",
"countryId": "IE",
"name": "Aviva Irl UK Equity Fund"
},
{
"id": "25000349",
"countryId": "IE",
"name": "New Ireland UK Equity 9"
}
]
},
{
"id": "25003339",
"countryId": "IE",
"name": "Irish Equity",
"Fund": [
{
"id": "25000279",
"countryId": "IE",
"name": "Friends First Irish Equity G"
},
{
"id": "25000305",
"countryId": "IE",
"name": "Irish Life Celticscope 2 G"
}
]
}
]
},
{
"id": "80",
"countryId": "IE",
"name": "Irish Individual Pensions",
"Category": [
{
"id": "25003347",
"countryId": "IE",
"name": "Asia Pacific Ex-Japan Equity",
"Fund": [
{
"id": "25001789",
"countryId": "IE",
"name": "Aviva Irl Pacific Basin Eq"
},
{
"id": "25002260",
"countryId": "IE",
"name": "Ir Life Pacific Eq Indexed P"
}
]
},
{
"id": "25003365",
"countryId": "IE",
"name": "Flexible Equity",
"Fund": [
{
"id": "25003238",
"countryId": "IE",
"name": "Friends First Protected Equity Plus Fund S2"
},
{
"id": "25003267",
"countryId": "IE",
"name": "Friends First Protected Equity Plus Bond G"
}
]
}
]
}
]
}
}
我需要做什么才能让它工作?
编辑为包含MonthlyPerformance
【问题讨论】:
-
你认为你的代码是指你定义的类型还是.net中预定义的
Type。也看看james.newtonking.com/projects/json-net.aspx -
嗨@DarthVader,我可以看到
Type的类型在我自己的命名空间中。即使我将其更改为尝试创建MonthlyPerformance的实例(我已经用这个更新了问题),它的行为仍然相同。
标签: c# json json.net deserialization