Deserialize json object into dynamic object using Json.net

后端 未结 8 1722
感情败类
感情败类 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:56

    If you just deserialize to dynamic you will get a JObject back. You can get what you want by using an ExpandoObject.

    var converter = new ExpandoObjectConverter();    
    dynamic message = JsonConvert.DeserializeObject<ExpandoObject>(jsonString, converter);
    
    0 讨论(0)
  • 2020-11-21 22:59

    Json.NET allows us to do this:

    dynamic d = JObject.Parse("{number:1000, str:'string', array: [1,2,3,4,5,6]}");
    
    Console.WriteLine(d.number);
    Console.WriteLine(d.str);
    Console.WriteLine(d.array.Count);
    

    Output:

     1000
     string
     6
    

    Documentation here: LINQ to JSON with Json.NET

    See also JObject.Parse and JArray.Parse

    0 讨论(0)
提交回复
热议问题