如何从json对象获取密钥并转换为数组?

时间:2016-12-15 18:31:51

标签: c# .net json

{
 "Date": "2016-12-15",
 "Data": {
   "A": 4.4023,
   "AB": 1.6403,
   "ABC": 2.3457
 }
}

如何将我的钥匙A,Ab,ABC变成阵列?只是键没有价值。

2 个答案:

答案 0 :(得分:1)

您可以安装并使用LINQ to JSON查询属性:

var jsonString = @"{
     ""Date"": ""2016-12-15"",
     ""Data"": {
       ""A"": 4.4023,
       ""AB"": 1.6403,
       ""ABC"": 2.3457
     }
}";

var root = JToken.Parse(jsonString);

var properties = root
    // Select nested Data object
    .SelectTokens("Data")
    // Iterate through its children, return property names.
    .SelectMany(t => t.Children().OfType<JProperty>().Select(p => p.Name))
    .ToArray();

Console.WriteLine(String.Join(",", properties)); // Prints A,AB,ABC

示例fiddle

答案 1 :(得分:0)

您可以使用内置的JavaScriptSerializer反序列化为object。在这种情况下,任何JSON对象实际上都会被反序列化为IDictionary<string, object>。然后,您可以将返回的object强制转换为此类字典,并(递归地)查询其内容,包括其键和值:

var jsonString = @"{
     ""Date"": ""2016-12-15"",
     ""Data"": {
       ""A"": 4.4023,
       ""AB"": 1.6403,
       ""ABC"": 2.3457
     }
}";

var root = new JavaScriptSerializer().Deserialize<object>(jsonString);

var properties = root
    // Select nested Data object
    .JsonPropertyValue("Data")
    // Iterate through its children, return property names.
    .JsonPropertyNames()
    .ToArray();

Console.WriteLine(String.Join(",", properties)); // Prints A,AB,ABC

使用扩展方法:

public static class JavaScriptSerializerObjectExtensions
{
    public static object JsonPropertyValue(this object obj, string key)
    {
        var dict = obj as IDictionary<string, object>;
        if (dict == null)
            return null;
        object val;
        if (!dict.TryGetValue(key, out val))
            return null;
        return val;
    }

    public static IEnumerable<string> JsonPropertyNames(this object obj)
    {
        var dict = obj as IDictionary<string, object>;
        if (dict == null)
            return null;
        return dict.Keys;
    }
}