C# uses dynamic type to access JObject object

dynamic is a dynamic type in C#, which can access the corresponding properties in the case of unknown types, which is very flexible and convenient.

Using Json.Net, you can convert a Json string into a JObject object. If there is a known strong type, if there is a known corresponding strong type, you can directly convert it to the corresponding type. But if not, it will be more troublesome to access the corresponding data in Json. We can use DynamicObject to access the corresponding properties.

DynamicObject

We want to create a dynamic class to access JObject, the code is as follows:

public class JObjectAccessor : DynamicObject
{
    JToken obj;

    public JObjectAccessor(JToken obj)
    {
        this.obj = obj;
    }

    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        result = null;
            
        if (obj == null) return false;

        var val = obj[binder.Name];

        if (val == null) return false;

        result = Populate(val);

        return true;
    }


    private object Populate(JToken token)
    {
        var jval = token as JValue;
        if (jval != null)
        {
            return jval.Value;
        }
        else if (token.Type == JTokenType.Array)
        {
            var objectAccessors = new List<object>();
            foreach (var item in token as JArray)
            {
                objectAccessors.Add(Populate(item));
            }
            return objectAccessors;
        }
        else
        {
            return new JObjectAccessor(token);
        }
    }
}

 

Then you can start using it:

string json = @"{'name': 'Jeremy Dorn','location': {'city': 'San Francisco','state': 'CA'},'pets': [{'type': 'dog','name': 'Walter'}]}";

JObject jobj = JObject.Parse(json);

dynamic obj = new JObjectAccessor(jobj);

Console.WriteLine($"{obj.name}: {obj.location.city} {obj.location.state}");
Console.WriteLine($"{obj.pets[0].type}: {obj.pets[0].name}");

 

Run the program and see the output:

Original address: http://www.zkea.net/codesnippet/detail/post-99.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324500390&siteId=291194637