【问题标题】:Json Object to a Multidimensional C# Array?Json 对象到多维 C# 数组?
【发布时间】:2010-04-08 18:17:33
【问题描述】:

有没有办法将 Json 对象转换为多维 C# 数组?我知道这可能不切实际,但我懒得写类然后 反序列化 将字符串插入其中。

List<string> ohyeah = (List<string>)JsonConvert.DeserializeObject(g.CommToken);

这会返回一个 Invalid Cast 异常!

例子:

{"method":"getCommunicationToken","header":{"uuid":"9B39AAB0-49A6-AC7A-BA74-DE9DA66C62B7","clientRevision":"20100323.02","session":"c0d3e8b5d661f74c68ad72af17aeb5a1","client":"gslite"},"parameters":{"secretKey":"d9b687fa10c927f102cde9c085f9377f"}}

我需要得到类似的东西:

j["method"]; //This will equal to getCommunicationToken
j["header"]["uuid"]; //This will equal to 9B39AAB0-49A6-AC7A-BA74-DE9DA66C62B7

我确实需要将 json 对象解析为一个数组。

【问题讨论】:

  • 这太荒谬了!有这么多的f-ing库,没有一个能做这个简单的任务......
  • 您的问题不完整。提供您要使用的 json 示例。
  • 仅供参考...“List”不是多维数组。我想不出一个内置的集合类可以让你访问这样的数据。我唯一的想法是将其转换为 XML 文档,然后使用 XPath 获取所需的值。

标签: c# arrays json


【解决方案1】:

JObject 类的 Parse 和 SelectToken 方法完全可以满足您的需求。 图书馆可以在这里找到:http://json.codeplex.com/releases/view/37810

JObject o = JObject.Parse(@"
{
    ""method"":""getCommunicationToken"",
    ""header"":
    {
        ""uuid"":""9B39AAB0-49A6-AC7A-BA74DE9DA66C62B7"",
        ""clientRevision"":""20100323.02"",
        ""session"":""c0d3e8b5d661f74c68ad72af17aeb5a1"",
        ""client"":""gslite""
    },
    ""parameters"":
    {
        ""secretKey"":""d9b687fa10c927f102cde9c085f9377f""
    }
}");

string method = (string)o.SelectToken("method");
// contains now 'getCommunicationToken'

string uuid = (string)o.SelectToken("header.uuid");
// contains now '9B39AAB0-49A6-AC7A-BA74DE9DA66C62B7'

顺便说一句:这不是多维数组:

j["header"]["uuid"];

例如,您可以将这些索引器放在以字典为值的字典中,例如:

Dictionary<string, Dictionary<string, string>> j;

但在这里你只会有两个索引的“深度”。如果您想要一个带有这种“锯齿状数组样式”的索引器的数据结构,您可以编写如下类:

class JaggedDictionary{
    private Dictionary<string, string> leafs = 
            new Dictionary<string, string>();
    private Dictionary<string, JaggedDictionary> nodes = 
            new Dictionary<string, JaggedDictionary>();

    public object this[string str]
    {
        get
        {
            return nodes.Contains(str) ? nodes[str] : 
                   leafs.Contains(str) ? leafs[str] : null;
        }
        set
        {
            // if value is an instance of JaggedDictionary put it in 'nodes',
            // if it is a string put it in 'leafs'...
        }
    }
}

【讨论】:

    猜你喜欢
    • 2018-12-18
    • 1970-01-01
    • 1970-01-01
    • 2012-10-07
    • 2015-11-23
    • 1970-01-01
    • 1970-01-01
    • 2012-08-09
    • 1970-01-01
    相关资源
    最近更新 更多