C ා use dynamic type to access jobobject object

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

Using Json.Net, you can convert a Json string to a job object. If you have a known strong type, if you have a known strong type, you can directly convert it to the corresponding type. But if not, it is 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 the job object. 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 following program to see the output:

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

Keywords: C# JSON

Added by timgolding on Sat, 04 Apr 2020 17:38:18 +0300