gpt4 book ai didi

.net - 当 JSON 未反序列化为我的对象时如何抛出异常

转载 作者:行者123 更新时间:2023-12-02 00:23:43 24 4
gpt4 key购买 nike

我正在针对 .NET 中的 RESTful Web 服务(JSON 负载)编写测试自动化,并想验证发送给我的对象是否完全我定义的 DTO 中的字段,而不是更多或更少。

但是,当对象类型不匹配时,我使用的序列化方法(System.Web.Script.Serialization)似乎并不介意。

    private class Dog
{
public string name;
}
private class Cat
{
public int legs;
}
static void Main(string[] args)
{
var dog = new Dog {name = "Fido"};
var serializer = new JavaScriptSerializer();
String jsonString = serializer.Serialize(dog);
var deserializer = new JavaScriptSerializer();
Cat cat = (Cat)deserializer.Deserialize(jsonString, typeof(Cat));
//No Exception Thrown! Cat has 0 legs.
}

是否有支持此要求的 .NET 序列化库?其他方法?

最佳答案

您可以使用 JSON 架构验证解决此问题。最简单的方法是使用 Json.NET 的架构反射功能。 ,像这样:

using System.Diagnostics;
using Newtonsoft.Json;
using Newtonsoft.Json.Schema;

public class Dog
{
public string name;
}

public class Cat
{
public int legs;
}

public class Program
{
public static void Main()
{
var dog = new Dog {name = "Fido"};

// Serialize the dog
string serializedDog = JsonConvert.SerializeObject(dog);

// Infer the schemas from the .NET types
var schemaGenerator = new JsonSchemaGenerator();
var dogSchema = schemaGenerator.Generate(typeof (Dog));
var catSchema = schemaGenerator.Generate(typeof (Cat));

// Deserialize the dog and run validation
var dogInPotentia = Newtonsoft.Json.Linq.JObject.Parse(serializedDog);

Debug.Assert(dogInPotentia.IsValid(dogSchema));
Debug.Assert(!dogInPotentia.IsValid(catSchema));

if (dogInPotentia.IsValid(dogSchema))
{
Dog reconstitutedDog = dogInPotentia.ToObject<Dog>();
}
}
}

您可以找到有关 here 功能的更多一般信息.

关于.net - 当 JSON 未反序列化为我的对象时如何抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9779476/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com