How to get Key from nested object with a Json Obje

2019-09-07 12:20发布

问题:

This question already has an answer here:

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

I have a Json object which returns json.

I call an api and convert into json object:

var returnJson = new JavaScriptSerializer().Deserialize(removeChar, targetType: null);

The results are:

{
  "Type": "Local",
  "results": {
    "A": 4.4023,
    "B": 1.6403,
    "C": 2.3457
}

how do I do literate through this json object and return just keys in array?

I unsure what goes in foreach loop:

foreach(var item in returnJson)
{
//get just keys.ToArray();
}

class file

public class BasicResults
    {
        public string Type { get; set; }
        public  Result results { get; set; }
    }

 public class Result
    {
      public double A { get; set; }
      public double B { get; set; }
      public double C { get; set; }
    }
}

I think this is in the right direction but can not target nested rate:

object[] getResults = returnJson.GetType()
                         .GetProperties()
                         .Select(p =>
                         {
                             object value = p.GetValue(results);
                             return value == null ? null : value.ToString();
                         })
                         .ToArray();

回答1:

Create a class like below

public class JsonData
{
    public string Type { get; set; }
    public Dictionary<string, string> Results { get; set; }
}

And the do the Deserialize

var returnJson = new JavaScriptSerializer().Deserialize<JsonData>(yourJsonString);

Then you can get the keys

 var keys = returnJson .Results.Keys;


标签: c# arrays json key