【问题标题】:List values by key in deserialized json object在反序列化的 json 对象中按键列出值
【发布时间】:2015-07-02 02:04:23
【问题描述】:

所以我定义

public class Globals
{
    public List<object> var { get; set; }
}

我发送的json是这样的

{"var":[{"test1":"1","test2","2","test3","3"}],"morejson":"blahblahblah}

假设我现在有了这个,我们假设 AppendTextBox 正在单独的线程中编写一个文本框

void getmedata()
{
    var commands = JsonParser.Deserialize<Globals>(json);

    AppendTextBox(commands.description[0].ToString()); 
    AppendTextBox(commands.description.Count.ToString());
}

AppendTextBox(commands.description.Count.ToString()); 工作并显示计数

但是,我似乎无法让它更好地按键打印值。它的设置方式目前提供以下输出

System.Collections.Generic.Dictionary`2[System.String,System.Object]`

有什么建议吗?

【问题讨论】:

  • 为什么没有强类型对象而不是object 项目的集合?
  • 好问题。这是因为 json 来自另一台机器,它有可能是 1,2 或 3 项。
  • 如果您将格式更改为:{"var":[{"test1":"1"},{"test2","2 "},{"test3","3"}],"morejson":"blahblahblah} 然后将其作为对象数组引入并从那里执行 ToDictionary。

标签: c# json object


【解决方案1】:

您可以使用ListDictionary 代替object 来访问它:

public class Globals
{
    public List<Dictionary<string, string>> var { get; set; }
}

然后,你的 JSON

{"var":[{"test1":"1","test2","2","test3","3"}, {"anykey1": "anyvalue1", "anykey2": "anyvalue2"}, {}, {"1": "2"}], "morejson": "blahblahblah"}

将转换为长度为 4 的 List。每个键将代表一个 Dictionary&lt;string, string&gt;

例如,如果你这样做:

foreach (var keyValuePair in commands[1])
{
     Console.WriteLine("{0} => {1}", keyValuePair.Key, keyValuePair.Value);
}

你会得到

anykey1 => anyvalue1
anykey2 => anyvalue2

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-20
    • 2015-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多