使用 Newtonsoft 反序列化多态 json 对象



我实际上尝试根据 Patreon 反序列化单元测试中的下一个对象

string json = @"{
            ""data"": {
                ""attributes"": {
                    ""about"": """",
                    ""created"": ""2017-04-01T12:00:00+00:00"",
                    ""discord_id"": null,
                    ""email"": ""james@mymail.com"",
                    ""facebook"": null,
                    ""facebook_id"": null,
                    ""first_name"": ""Firstname"",
                    ""full_name"": ""Fullname"",
                    ""gender"": 0,
                    ""has_password"": true,
                    ""image_url"": ""https://c3.patreon.com/2/patreon-user/abc.jpg"",
                    ""is_deleted"": false,
                    ""is_email_verified"": true,
                    ""is_nuked"": false,
                    ""is_suspended"": false,
                    ""last_name"": """",
                    ""social_connections"": {
                        ""deviantart"": null,
                        ""discord"": null,
                        ""facebook"": null,
                        ""spotify"": null,
                        ""twitch"": null,
                        ""twitter"": null,
                        ""youtube"": null
                    },
                    ""thumb_url"": ""https://c3.patreon.com/2/patreon-user/abc.jpg"",
                    ""twitch"": null,
                    ""twitter"": null,
                    ""url"": ""https://www.patreon.com/user?u=123456"",
                    ""vanity"": null,
                    ""youtube"": null
                },
                ""id"": ""123456"",
                ""relationships"": {
                    ""pledges"": {
                        ""data"": []
                    }
                },
                ""type"": ""user""
            },
            ""links"": {
                ""self"": ""https://api.patreon.com/user/123456""
            }
            }";

但是我的属性对象或数组是多态的,它可以像我的示例一样是用户,但其他对象类型,我不知道该怎么做。
我尝试过这样的事情,但没有成功。

第二个问题,如何通过 id 和关系将同一用户类中的属性扁平化。

编辑:为了回答我的问题,我找到了比"重复"更好的解决方案:http://jsonapi.org/

不,不行。

Newtonsoft.JSON 包具有在序列化对象时包含类型名称的选项,因此反序列化可以正确使用多态性。 但是对于普通的 JSON,反序列化程序无法知道要在数组中实例化哪个类。

最新更新