Deserialize json object into dynamic object using Json.net

后端 未结 8 1740
感情败类
感情败类 2020-11-21 22:07

Is it possible to return a dynamic object from a json deserialization using json.net? I would like to do something like this:

dynamic jsonResponse = JsonConv         


        
8条回答
  •  忘掉有多难
    2020-11-21 22:42

    If you use JSON.NET with old version which didn't JObject.

    This is another simple way to make a dynamic object from JSON: https://github.com/chsword/jdynamic

    NuGet Install

    PM> Install-Package JDynamic
    

    Support using string index to access member like:

    dynamic json = new JDynamic("{a:{a:1}}");
    Assert.AreEqual(1, json["a"]["a"]);
    

    Test Case

    And you can use this util as following :

    Get the value directly

    dynamic json = new JDynamic("1");
    
    //json.Value
    

    2.Get the member in the json object

    dynamic json = new JDynamic("{a:'abc'}");
    //json.a is a string "abc"
    
    dynamic json = new JDynamic("{a:3.1416}");
    //json.a is 3.1416m
    
    dynamic json = new JDynamic("{a:1}");
    //json.a is integer: 1
    

    3.IEnumerable

    dynamic json = new JDynamic("[1,2,3]");
    /json.Length/json.Count is 3
    //And you can use json[0]/ json[2] to get the elements
    
    dynamic json = new JDynamic("{a:[1,2,3]}");
    //json.a.Length /json.a.Count is 3.
    //And you can use  json.a[0]/ json.a[2] to get the elements
    
    dynamic json = new JDynamic("[{b:1},{c:1}]");
    //json.Length/json.Count is 2.
    //And you can use the  json[0].b/json[1].c to get the num.
    

    Other

    dynamic json = new JDynamic("{a:{a:1} }");
    
    //json.a.a is 1.
    

提交回复
热议问题