how to get the key from json object and convert into an array?

前端 未结 2 728
醉话见心
醉话见心 2020-12-22 09:44
{
 \"Date\": \"2016-12-15\",
 \"Data\": {
   \"A\": 4.4023,
   \"AB\": 1.6403,
   \"ABC\": 2.3457
 }
}

how can i get my keys A,Ab,ABC into an array

相关标签:
2条回答
  • 2020-12-22 10:11

    You could install json.net and use LINQ to JSON to query the properties:

    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
    

    Sample fiddle.

    0 讨论(0)
  • 2020-12-22 10:14

    You could use the built-in JavaScriptSerializer to deserialize to an object. In this case, any JSON object will actually get deserialized to an IDictionary<string, object>. Then you can cast the returned object to such a dictionary and (recursively) query its contents including its keys and values:

    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
    

    Using the extension methods:

    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;
        }
    }
    
    0 讨论(0)
提交回复
热议问题