简体   繁体   English

将Json字符串反序列化为自定义.Net对象

[英]Deserialize Json string into custom .Net object

I have very big plain json from server with format like this 我有来自服务器的非常大的普通json,格式如下

{ "A": 1, "B" : 2, "C" : 3 }

I can't change format. 我不能改变格式。

But instead of making one megaclass 但不是制造一个巨型物

public class MegaClass
{
    public int A;
    public int B;
    public int C;
}

I want to group some properties to another object, like this 我想将一些属性分组到另一个对象,就像这样

public class MegaClass
{
    public int A;
    public SetOfVariables1 Set1;
}

public class SetOfVariables1
{
     public int B;
     public int C;
}

Is there way to make this work? 有没有办法让这项工作?

The bad news is, I would guess that you can't make that dynamicly. 坏消息是,我猜你不能动态地做到这一点。 The good news is, that you can handle the deserialization yourself and generate from there your object. 好消息是,您可以自己处理反序列化并从那里生成您的对象。

I guess you are doing this to get a nicer structure, but be aware that you have to write your own serializer if you want to get the object back into its original structure. 我猜你这样做是为了获得一个更好的结构,但要注意 ,如果你想让对象恢复到原来的结构,你必须编写自己的序列化器

I have found two options to achieve the result you are trying to get. 我找到了两个选项来实现你想要获得的结果。 I am no pro when it comes to Json.NET, in fact its fairly new to me. 对于Json.NET,我不是专业人士,事实上它对我来说相当新。

Here Comes the code: 这里有代码:

class Program
{
    static void Main(string[] args)
    {
        String json = "{ 'A': 1, 'B' : 2, 'C' : 3 }";
        var classA = JsonConvert.DeserializeObject<MegaClass>(json,new AConverter());
        var classA2 = JsonConvert.DeserializeObject<MegaClass2>(json);
    }

    public class MegaClass2
    {
        public int A { get; set; }
        public SetOfVariables SetOfVariables1 { get; set; }

        public MegaClass2()
        {
            _additionalData = new Dictionary<string, JToken>();
            SetOfVariables1 = new SetOfVariables();
        }

        [JsonExtensionData]
        private IDictionary<string, JToken> _additionalData;

        [OnDeserialized]
        private void OnDeserialized(StreamingContext context)
        {
            int b = (int)_additionalData["B"];
            int c = (int)_additionalData["C"];

            SetOfVariables1.B = b;
            SetOfVariables1.C = c;
        }
    }

    public class MegaClass
    {
        public int A { get; set; }
        public SetOfVariables SetOfVariables1 { get; set; }
    }

    public class SetOfVariables
    {
        public int B { get; set; }
        public int C { get; set; }
    }

    public class AConverter : CustomCreationConverter<MegaClass>
    {
        public override MegaClass Create(Type objectType)
        {
            throw new NotImplementedException();
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            dynamic cl = serializer.Deserialize(reader);
            var classA = new MegaClass();
            classA.A = cl.A;
            var classB = new SetOfVariables();
            classB.B = cl.B;
            classB.C = cl.C;
            classA.SetOfVariables1 = classB;
            return classA;
        }
    }
}

So here is the descritption: The first option uses the CustomCreationConverter. 所以这里是descritption:第一个选项使用CustomCreationConverter。 We deserialize the object into its original representation and create from there a new one. 我们将对象反序列化为其原始表示,并从那里创建一个新对象。

The second option seems to initialize our object after it was deserialized. 第二个选项似乎在反序列化后初始化我们的对象。 The _additionalData is set by the framework and we simply use it to fill our object. _additionalData由框架设置,我们只是用它来填充我们的对象。

I saw the first option been used to create different objects according to the json provided. 我看到第一个选项用于根据提供的json创建不同的对象。 For example if you have a class A and Class B and both extend Class C then you can decide in the overriden Create method which object to deserialize. 例如,如果你有一个A类B类并且都扩展了C类,那么你可以在重写Create方法中决定反序列化哪个对象。

The first option is inspired by the Json.NET documentation 第一个选项的灵感来自Json.NET 文档

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

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