反序列化时是否有可能以某种方式捕获与任何 POCO 属性都不匹配的剩余 JSON 数据? [英] Is it possible to catch somehow the remainder of JSON data that didn't match any POCO properties while deserializing?

查看:26
本文介绍了反序列化时是否有可能以某种方式捕获与任何 POCO 属性都不匹配的剩余 JSON 数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从外部 API 获取一些 JSON 数据.我有数据反序列化的 POCO 对象.我使用 System.Text.Json.JsonSerializer 进行反序列化.最近,我意识到我收到的 JSON 的结构发生了变化,我只是在检查其他东西时偶然知道它.我的问题是,是否有可能以某种方式捕获未成功映射到任何 POCO 字段的 json 数据?

I'm getting some JSON data from the external API. I have my POCO objects to which the data is deserialized. I use System.Text.Json.JsonSerializer for deserialization. Recently, I realized that the structure of the JSON that I receive has changed and I got to know it only by accident while checking something else. My question is, is it possible to catch somehow the json data that didn't succeed to be mapped to any POCO fields?

为了更准确地回答我的问题,这里是一个 POCO 示例:

To be more precise with my question here is an example POCO:

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

我之前收到的 JSON:

JSON that I received before:

{"Name" : "PinkCar", "Age": 3}

我现在收到的 JSON:

JSON that I receive now:

{"Name" : "PinkCar", "Age": 3, "RogueField": "Loser"}

我希望至少能够以某种方式获得有关这个新的RogueField"的信息.在不破坏反序列化过程的情况下不匹配任何 POCO 属性.

I would like to be able to at least get somehow information that there is this new "RogueField" that doesn't match any POCO properties without breaking the process of deserialization.

推荐答案

额外的属性可以与您的对象一起保存在字典中.你可以操作这个目录,当你再次序列化你的对象时会用到它.

Extra properties can be saved in a dictionary with your object. You can manipulate this directory and it will be used when serializing your object again.

来自 https://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-how-to#handle-overflow-json:创建 Dictionary<string, object>,这可以有任何名字(大多数情况下这是命名为ExtensionData但可以是任何东西),并用[JsonExtensionData]属性修饰它,例如:

From https://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-how-to#handle-overflow-json: Create a property of the type Dictionary<string, object>, this can have any name (mostly this is named ExtensionData but can be anything), and decorate it with the [JsonExtensionData] attribute, for example:

public class Car
{
    public string Name { get; set; }
    public int Age { get; set; }
    [JsonExtensionData]
    public Dictionary<string, object> ExtensionData { get; set; }
}

这篇关于反序列化时是否有可能以某种方式捕获与任何 POCO 属性都不匹配的剩余 JSON 数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆