【问题标题】:JSON dynamic object - Perl-like conversionJSON 动态对象 - 类 Perl 转换
【发布时间】:2015-01-06 00:26:12
【问题描述】:

我正在使用 Windows Phone 8.1 SDK。 我正在尝试将 JSON 字符串转换为动态对象。这与大多数情况不同,因为就像 Facebook API 一样,没有预定义的类可以关联字符串。 具体来说,我有一个 json 字符串,如:

{
    "indexes": {
        "000000": "3d6d0abf0ae645eaf8bf090a2685c29a",
        "000001": "3d6d0abf0ae645eaf8bf090a2685c29a"
    }
}

等等。这意味着我不能明显地将类与对象相关联,因为属性名称是动态的。我想要的是能够遍历这些值,记住层次结构是“indexes”->“000000”->Value、“indexes”->“000001”->Value、“indexes”->“。 ..”->值。 我查看了 JSON.NET ,试图反序列化为 ExpandoObject,但这不起作用,因为看起来 ExpandoObjectConverter 给出了一堆编译错误,可能是因为 Windows Phone 8.1 环境? 无论如何,我有点碰壁了,所以欢迎任何建议。

编辑:我的示例选择不当,我需要的是更通用的转换,因为它可能是一个递归结构,其中可能缺少一个或多个字段,例如:

{
    "friends": {
        "020709": {
               "JohnSmith" : {
                               "email": "johnsmith@something",
                               "mobile": "110011001100"
                             }
                  },
        "010305": {
               "PaulRoss" : {
                               "address": "Some way or the other",
                               "email": "paulross@something",
                             }
                  }
               }}

这在 Perl 中很容易做到,因为有通用哈希映射,但在 C# 中似乎没有真正的等价物?

【问题讨论】:

标签: c# json serialization dynamic json.net


【解决方案1】:

如果您的数据是高度可变的,并且您不想创建严格的类结构,那么最好的办法是反序列化为JToken,然后使用LINQ-to-JSON API 从中提取您需要的数据。这是一个例子:

string json = @"
{
    ""friends"": {
        ""020709"": {
            ""JohnSmith"": {
                ""email"": ""johnsmith@something"",
                ""mobile"": ""110011001100""
            }
        },
        ""010305"": {
            ""PaulRoss"": {
                ""address"": ""Some way or the other"",
                ""email"": ""paulross@something""
            }
        }
    }
}";

JToken root = JToken.Parse(json);
foreach (JProperty idProp in root["friends"])
{
    foreach (JProperty nameProp in idProp.Value)
    {
        JToken details = nameProp.Value;
        Console.WriteLine("id: " + idProp.Name);
        Console.WriteLine("name: " + nameProp.Name);
        Console.WriteLine("address: " + (string)details["address"]);
        Console.WriteLine("email: " + (string)details["email"]);
        Console.WriteLine("mobile: " + (string)details["mobile"]);
        Console.WriteLine();
    }
}

输出:

id: 020709
name: JohnSmith
address:
email: johnsmith@something
mobile: 110011001100

id: 010305
name: PaulRoss
address: Some way or the other
email: paulross@something
mobile:

【讨论】:

  • 非常感谢!这正是我一直在寻找的,我会将其标记为答案。
  • 没问题;很高兴我能帮上忙。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-10-13
  • 2014-02-08
  • 2011-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多