In JSON's back -sequentialization, it is important to deal with missing fields. By default, the serializer of JSON.NET will quietly return to silence when encountering missing fields. This behavior may lead to unlimited errors when an object with incorrect deepertization attributes.
question:
You encounter a problem, that is, JSON.NET serializers will not throw abnormalities when the objects that lack fields lack fields. Instead, it returns silent value, which makes it difficult to detect incorrect data.
solution:
JSON.NET provides a configurable MissionMemberhandling settings. By setting it to
error, you can indicate that the serializer causes jsonserializationException
when encountering missing fields during the desertification period. In this way, you can explicitly handle such errors in the code.
code:
using newtonsoft.json;
try
{{
// Read the json string
Const String Correctdata = @"{'Myjsonint': 42}";
Const String WrongData = @"{'Someotherproperty': 'Fbe8c20b'}";
// Create serializer settings
JsonSerializerSettings settings = New JSONSERIALATETNGS ();
settings.missingMemberhandling = missingMemberhandling.error;
// Reverse sequentialization object
var goodObj = jsonConvert.DeserializeObject
Output:
42 JSONSERIALIONEXCEUON: COULD Not Find Member 'SomeotherProperty' on Object of type 'myjsonobjView'. Path 'SomeotherProperty', LINE 3, Position 33.using Newtonsoft.Json;
try
{
// 读取JSON字符串
const string correctData = @"{ 'MyJsonInt': 42 }";
const string wrongData = @"{ 'SomeOtherProperty': 'fbe8c20b' }";
// 创建序列化器设置
JsonSerializerSettings settings = new JsonSerializerSettings();
settings.MissingMemberHandling = MissingMemberHandling.Error;
// 反序列化对象
var goodObj = JsonConvert.DeserializeObject(correctData, settings);
Console.WriteLine(goodObj.MyJsonInt.ToString());
var badObj = JsonConvert.DeserializeObject(wrongData, settings);
Console.WriteLine(badObj.MyJsonInt.ToString());
}
catch (Exception ex)
{
Console.WriteLine(ex.GetType().Name ": " ex.Message);
}
to Error , we ensure that the serializer will throw out the object of the lack of fields jsonserizationException
allows you to handle errors and ensure that Data Pottery.Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3