简体   繁体   中英

Convert a JSON object/string to a C# dynamic object and have access to the properties/values?

I am trying to take a huge JSON file (could be a string) and without knowing the actual structure of the data I want to read and process it as a class in C#. I tried using JSON to deserialize it but I wasn't totally sure about where to go after that. I was thinking of using Reflections but not sure what data I need.

I have tried to deserialize the object as the code shows. But I want to test if it is the right object type incase it isn't I would hope it fails but I can't seem to get past this part. I also am not sure what to do with reflections inside of the check. I know I should iterate but not sure which property values inside of the object will contain what I need.

string jsonData = sr.ReadToEnd();
dynamic data = JsonConvert.DeserializeObject(jsonData);
if (data is List<dynamic>)
{
    data.GetType().GetProperties();
}

I want an object that has all the access to the data from a JSON file/string.

I think one of your problems is to use JArray instead of List and also you need to cast your item to JObject. Use Newtonsoft.Json and Newtonsoft.Json.Linq then you can read your Json as an example:

string __content = "[ {\"name\": \"person1\" , \"age\": 33} , {\"name\": \"person2\" , \"age\" : 23} ]";

        dynamic data = JsonConvert.DeserializeObject(__content);
        // make sure you have an array of object
        if (data is Newtonsoft.Json.Linq.JArray)
        {
            int i = 0;
            foreach (dynamic item in data)
            {
                // get the property of the object 
                JObject currentitem = item as JObject;
                if (currentitem != null)
                {
                    // access to value of each property
                    foreach (JProperty p in currentitem.Properties())
                    {
                        Console.WriteLine("[" + i + "] : " + p.Name + ":" + p.Value.ToString());
                    }
                    i++;
                }
            }
        }

You can use the DeserializeObject method with a generic type. In order to assure the Type you want to cast to. Which mean your code will be as following:

var data = JsonConvert.DeserializeObject<T>(jsonData);

Where T is the class you want to parse to. This method will throw an exception in case the Json string can't be parsed to your class. I think that's what you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM