简体   繁体   English

C# 将 JSON 对象序列化为一个类

[英]C# serialize JSON Object to a class

I am working on Json Obejct deserielize to a class in .net VS2015 on win 7.我正在将 Json Obejct 反序列化为 Win 7 上的 .net VS2015 中的一个类。

public class1
{
    [JsonProperty(TypeNameHandling = TypeNameHandling.Objects)]
    public Class1 data1;
    public Class2 data2;
}

public abstract Class1 
{
    some functions

}

public subClass1 : Class1
{
        public string myData1 { get; set; }
        public string myData2 { get; set; }

}

In my code of deserierlizing:在我的反序列化代码中:

var mo = MyObject as JObject;

ParentMyClass = mo.ToObject<MyClass>();

I know that an abstract class cannot be instantiated.我知道抽象类不能被实例化。 So, subClass1 (which is one of the implementation of Class1) is serialized.因此,subClass1(它是 Class1 的实现之一)被序列化。 But, subClass1 is null after deserialized.但是,反序列化后 subClass1 为空。

Did I do something wrong ?我做错什么了吗 ?

UPDATED: because the code of the classes is too complex, I just simplified the logic.更新:因为类的代码太复杂,我只是简化了逻辑。

When you call mo.ToObject<Class1>();当你调用mo.ToObject<Class1>(); Newtonsoft.Json library will try to create an instance down the line. Newtonsoft.Json 库将尝试创建一个实例。 The problem is you cannot instantiate a abstract.问题是你不能实例化一个抽象。 You can see this your self by calling var x = new Class1();您可以通过调用var x = new Class1();来查看自己的情况var x = new Class1(); somewhere in you code.在你的代码中的某个地方。 This will give you error.这会给你错误。

That being said, one thing you could do is create another class that inherits the abstract class.话虽如此,您可以做的一件事是创建另一个继承抽象类的类。

public class NonAbstract : Class1 {}

this way you will have a class that can be instantiated.这样,您将拥有一个可以实例化的类。 And then you can do this.然后你就可以做到这一点。

mo.ToObject<NonAbstract >();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM