JSON 反序列化 .net Core 3
JSON Deserialize .net Core 3
这个真的很基础。
使用新的 System.Text.Json;
反序列化字符串
namespace test
{
struct CI {
public int Id;
public string Name;
public string Address;
}
public class test{
var userlist = "{\"Id\":1,\"Name\":\"Manas\",\"Address\":\"India\"}";
var temp2 = JsonSerializer.Deserialize<CI>(userlist,new JsonSerializerOptions { AllowTrailingCommas = true});
}
}
但是这样做
我只是在 temp2
中为字符串得到 null,为 Int 得到 0
这一定很简单,但我不明白
System.Text.Jsondoesn't support field serialization。该功能计划用于 .NET 5.0。
您使用了 public 字段而不是 public 属性。如果您尝试使用属性和完全相同的代码:
struct CI {
public int Id {get;set;}
public string Name {get;set;}
public string Address {get;set;}
}
你会得到预期的对象:
Id 1
Name Manas
Address India
为什么?
System.Text.JSON 并不像 JSON.NET 那样是一把瑞士刀 JSON 反序列化器。它的主要用例是在 HTTP API 场景中以最少的分配进行快速 DTO 序列化,并且 DTO 使用属性。
属性不仅仅是带有 getter 和 setter 的字段,它们是对象接口的一部分。另一方面,字段被视为内部状态,即使它们是 public。默认情况下,序列化程序使用 properties,字段序列化是一项可选功能。
也就是说,值元组。现在这是一种基本类型,它使用字段来提高性能和减少复制。元组在 DTO 中占有一席之地,但当前的 System.Text.Json 无法处理它们。
Work is already well under way for this,已经有一个 PR 正在审核,但目标版本是 5.0
这个真的很基础。 使用新的 System.Text.Json;
反序列化字符串namespace test
{
struct CI {
public int Id;
public string Name;
public string Address;
}
public class test{
var userlist = "{\"Id\":1,\"Name\":\"Manas\",\"Address\":\"India\"}";
var temp2 = JsonSerializer.Deserialize<CI>(userlist,new JsonSerializerOptions { AllowTrailingCommas = true});
}
}
但是这样做
我只是在 temp2
这一定很简单,但我不明白
System.Text.Jsondoesn't support field serialization。该功能计划用于 .NET 5.0。
您使用了 public 字段而不是 public 属性。如果您尝试使用属性和完全相同的代码:
struct CI {
public int Id {get;set;}
public string Name {get;set;}
public string Address {get;set;}
}
你会得到预期的对象:
Id 1
Name Manas
Address India
为什么?
System.Text.JSON 并不像 JSON.NET 那样是一把瑞士刀 JSON 反序列化器。它的主要用例是在 HTTP API 场景中以最少的分配进行快速 DTO 序列化,并且 DTO 使用属性。
属性不仅仅是带有 getter 和 setter 的字段,它们是对象接口的一部分。另一方面,字段被视为内部状态,即使它们是 public。默认情况下,序列化程序使用 properties,字段序列化是一项可选功能。
也就是说,值元组。现在这是一种基本类型,它使用字段来提高性能和减少复制。元组在 DTO 中占有一席之地,但当前的 System.Text.Json 无法处理它们。
Work is already well under way for this,已经有一个 PR 正在审核,但目标版本是 5.0