1

I want to deserialize a JSON string that I don't know its Type to an object of type Object and be able to access its properties using reflection. when I used this

object myObject = JsonConvert.DeserializeObject("{\'Id\':\'1\'}");

the type of myObject is of type JObjectand I am not able to access its properties using reflection.

is there a way to do so using Json.net or any other JSON deserializer?

9
  • 1
    This seems like a duplicate of this: stackoverflow.com/questions/3142495/… Commented Dec 11, 2016 at 8:31
  • 1
    Or this with JSON.NET: stackoverflow.com/questions/4535840/… Commented Dec 11, 2016 at 8:33
  • @scotru I've tried the dynamic too. My point is that I need to access its properties using reflection. the generated dynamic object is also of type JObject Commented Dec 11, 2016 at 8:40
  • Your question should be answered under this link: JSON deserialize Commented Dec 11, 2016 at 8:40
  • @AndreasM. I've tried the dynamic too. My point is that I need to access its properties using reflection. the generated dynamic object is also of type JObject Commented Dec 11, 2016 at 8:57

2 Answers 2

2

I think you can deserialize the object into either a Dictionary<string,string> or an expandoobject (also castable to IDictionary<string,object>) and then you don't need to use reflection to get at the properties, you can get them through the dictionary.

See: Deserialize Dynamic Json string using Newtonsoft JSON.NET

Sign up to request clarification or add additional context in comments.

2 Comments

{"Id":"1"} is just a sample. The properties can be of any type, may be of a new object
Then you'd be better off using dynamic I'd say
1

This doesn't let you use reflection per-se but an ExpandoObject does let you iterate over the properties:

        string json = "{\'Id\':\'1\'}";
        var converter = new ExpandoObjectConverter();
        dynamic obj = JsonConvert.DeserializeObject<ExpandoObject>(json, converter);

        IDictionary<string, object> dict = (IDictionary<string, object>)obj;
        foreach (string key in dict.Keys)
        {
            Console.WriteLine(key);
        }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.