带动态名称问题的c#动态json对象

时间:2011-07-29 15:02:32

标签: c# json dynamic

在我被标记为重复之前,我让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 个答案:

答案 0 :(得分: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的博文:Quick JSON Serialization/Deserialization in C#

答案 1 :(得分: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"];

现在这一切似乎很明显,但我只是没想到它。

再次感谢。

相关问题