deserialize json into .net object using json.net

百般思念 提交于 2019-12-11 02:19:32

问题


I am having a problem deserializing some JSON string back into .net objects. I have a container class which contains some information from external and there is a field call ClassType which defined what type of information is that and the actual content is in another property, which currently can be anything, so we define that as an Object type.

Following are the .net class definition which helps to understand the issue.

class ClassOne
{
    public string Name { get; set; }
    public int Age { get; set; }
}

class ClassTwo
{
    public string AddressLine { get; set; }
    public string AddressLine2 { get; set; }
}

class ClassThree
{
    public string Country { get; set; }
    public string Passport { get; set; }
}

class ContainerClass
{
    public string ClassType { get; set; }
    public object ClassContent { get; set; }
}

When getting the information from external in a JSON format it will be something like:

{"ClassType":"Class1","ClassContent":{"Name":"James","Age":2}}

I am using Newtonsoft JSON.net library to deserialize the JSON string. It seems like that the default deserialize function will just deserialize that into an Newtonsoft.Json.Linq.JContainer. I just wondering how can I write some Converter to deserialize the ClassContent based on the ClassType definition. Any code sample will be highly appreciated.


回答1:


I would go dynamic way, like:

string json = @"{""ClassType"":""Class1"",""ClassContent"":{""Name"":""James"",""Age"":2}}";

dynamic jObj = JObject.Parse(json);
if (jObj.ClassType == "Class1")
{
    Console.WriteLine("{0} {1}", jObj.ClassContent.Name, jObj.ClassContent.Age);
}

Since returning an object (ClassContent) doesn't mean much, and you have to cast it to a concrete class somehow (using some if's or switch).




回答2:


Sample:

var container = JsonConvert.DeserializeObject<ContainerClass>(json);
JContainer content = (JContainer)container.ClassContent;

switch(container.ClassType)
{
    case "Class1": return container.ToObject(typeof(ClassOne));
    ..    
}



回答3:


use dynamic and call .ToObject(Type type)

dynamic root = JObject.Parse(json)
return root["ClassContent"].ToObject(Type.GetType(root["ClassType"]))



回答4:


Try the following

 var jsonObject = JObject.Parse(jsonString);

 var result = jsonObject.ToObject(Type.GetType("namespace.className"));


来源:https://stackoverflow.com/questions/17858046/deserialize-json-into-net-object-using-json-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!