Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
369 views
in Technique[技术] by (71.8m points)

c# - Is it possible to catch somehow the remainder of JSON data that didn't match any POCO properties while deserializing?

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?

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 that I received before:

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

JSON that I receive now:

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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; }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...