我有一个具有 type 属性的类Tuple<int, int>,该类被分配了默认值(-1, -1)。我还有一个 json 字符串,表示该类的对象,并为元组属性分配了非默认值。当我尝试使用 Json.NET 反序列化 json 字符串时,返回的对象的属性具有默认值。如果我删除类定义中的属性默认分配,则 json 字符串将被正确反序列化。这似乎只发生在元组类型的属性上。例如,我尝试使用字符串属性,反序列化非默认值没有任何问题。
如何正确反序列化具有默认值的元组属性?这是我应该在 Json.NET 上报告的错误吗?
using System;
using Newtonsoft.Json;
namespace ConsoleApp1
{
public class MyClass
{
public Tuple<int, int> TuplePropertyWithDefault { get; set; } = new Tuple<int, int>(-1, -1);
public string StringPropertyWithDefault { get; set; } = "";
public Tuple<int, int> TuplePropertyWithoutDefault { get; set; }
public string StringPropertyWithoutDefault { get; set; }
public override string ToString()
{
return $"TuplePropertyWithDefault = {TuplePropertyWithDefault}\n" +
$"TuplePropertyWithoutDefault = {TuplePropertyWithoutDefault}\n" +
$"StringPropertyWithDefault = {StringPropertyWithDefault}\n" +
$"StringPropertyWithoutDefault = {StringPropertyWithoutDefault}\n";
}
}
class Program
{
static void Main(string[] args)
{
var expected = new MyClass();
expected.TuplePropertyWithDefault = new Tuple<int, int> (0, 0);
expected.TuplePropertyWithoutDefault = new Tuple<int, int> (0, 0);
expected.StringPropertyWithDefault = "test";
expected.StringPropertyWithoutDefault = "test";
var jsonString = JsonConvert.SerializeObject(expected).ToString();
var deserialized = JsonConvert.DeserializeObject<MyClass>(jsonString);
Console.WriteLine("Expected:");
Console.WriteLine(expected);
Console.WriteLine("Deserialized:");
Console.WriteLine(deserialized);
Console.ReadLine();
}
}
}
以 .Net Framework 4.7.2 为目标,并使用 Newtonsoft.Json 版本 12.0.2。
慕村225694
相关分类