Deserializing json to anonymous object in c#

前端 未结 5 1536
深忆病人
深忆病人 2020-12-11 00:56

How do I convert a string of json formatted data into an anonymous object?

相关标签:
5条回答
  • 2020-12-11 01:07

    using Newtonsoft.Json, use DeserializeAnonymousType:

    string json = GetJsonString();
    var anonType = new { Order = new Order(), Account = new Account() };
    var anonTypeList = new []{ anonType }.ToList(); //Trick if you have a list of anonType
    var jsonResponse = JsonConvert.DeserializeAnonymousType(json, anonTypeList);
    

    Based my answer off of this answer: https://stackoverflow.com/a/4980689/1440321

    0 讨论(0)
  • 2020-12-11 01:12

    C# 4.0 adds dynamic objects that can be used. Have a look at this.

    0 讨论(0)
  • 2020-12-11 01:20

    vb.net using Newtonsoft.Json :

    dim jsonstring = "..."
    dim foo As JObject = JObject.Parse(jsonstring)
    dim value1 As JToken = foo("key")
    
    
    e.g.:
    dim jsonstring = "{"MESSAGE":{"SIZE":"123","TYP":"Text"}}"
    dim foo = JObject.Parse(jsonstring)
    dim messagesize As String = foo("MESSAGE")("SIZE").ToString()
    'now in messagesize is stored 123 as String
    

    So you don't need a fixed structure, but you need to know what you can find there.

    But if you don't even know what is inside, than you can enumerate thru that JObject with the navigation members e.g. .first(), .next() E.g.: So you could implement a classical depth-first search and screening the JObject

    (for converting vb.net to c#: http://converter.telerik.com/)

    0 讨论(0)
  • 2020-12-11 01:21

    I think the closest you can get is dynamic in .NET 4.0

    The reason anonymous objects wouldn't work is because they're still statically typed, and there's no way for the compiler to provide intellisense for a class that only exists as a string.

    0 讨论(0)
  • 2020-12-11 01:23

    using dynamics is something like this:

    string jsonString = "{\"dateStamp\":\"2010/01/01\", \"Message\": \"hello\" }";
    dynamic myObject = JsonConvert.DeserializeObject<dynamic>(jsonString);
    
    DateTime dateStamp = Convert.ToDateTime(myObject.dateStamp);
    string Message = myObject.Message;
    
    0 讨论(0)
提交回复
热议问题