C# 动态 JSON 对象与动态名称问题

4
在我进行重复标记之前,我已经成功地使用来自Dynamic json object with numerical keys的代码。我的数字键问题是,不幸的是,我得到的JSON字符串最初是按年份分隔的,那么我应该使用反射在动态对象上创建一个动态属性,如果可以的话,如何操作?我知道对于动态对象,我不能使用obj["2010"]或obj[0]。在JavaScript中没有问题,只是想让它在C#中正常工作。有什么想法吗? 返回的JSON示例:
    {
"2010": [
    {
        "type": "vacation",
        "alloc": "90.00"
    },

另外,有时候年份作为第二个元素出现:

我无法控制这个 JSON。

    {
"year": [],
"2010": [
    {
        "type": "vacation",
        "alloc": "0.00"
    },
2个回答

5
也许我误解了你的问题,但是这是我如何处理的方法:
static void Main(string[] args) {

var json = @"
{
  '2010': [
  {
    'type': 'vacation',
    'alloc': '90.00'
  },
  {
    'type': 'something',
    'alloc': '80.00'
  }
]}";


var jss = new JavaScriptSerializer();
var obj = jss.Deserialize<dynamic>(json);

Console.WriteLine(obj["2010"][0]["type"]);

Console.Read();

}

这有帮助吗?

我写了一篇关于使用.NET进行JSON序列化/反序列化的博客文章:C#中快速JSON序列化/反序列化


谢谢,完全没想到这种方法可以让我将“年份”作为变量传递。再次感谢。 - kpcrash

1
我已经点赞了这个问题和JP的回答,很高兴在互联网上找到了这个。我提供了一个单独的答案,以简化其他人的使用情况。关键是:
dynamic myObj = JObject.Parse("<....json....>");

// The following sets give the same result 

// Names (off the root)
string countryName = myObj.CountryName;
// Gives the same as 
string countryName = myObj["CountryName"];

// Nested (Country capital cities off the root)
string capitalName = myObj.Capital.Name;
// Gives the same as
string capitalName = myObj["Capital"]["Name"]; 
// Gives the same as
string capitalName = myObj.Capital["Name"];

现在看起来一切都很明显,但我当时没有想到。
再次感谢。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接