【问题标题】:JSON Deserialize .net Core 3JSON反序列化.net Core 3
【发布时间】:2019-11-26 13:48:34
【问题描述】:

这个真的是Basic。 使用新的 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 中为 Strings 获得 null,为 Int 获得 0

这一定很简单,但我不明白

【问题讨论】:

    标签: json .net-core-3.0 system.text.json


    【解决方案1】:

    System.Text.Json doesn't support field serialization。该功能计划用于 .NET 5.0。

    您使用了公共字段而不是公共属性。如果您尝试使用属性和完全相同的代码:

        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 的字段,它们是对象接口的一部分。另一方面,即使字段是公开的,它们也会被视为内部状态。默认情况下,序列化程序使用 properties,字段序列化是可选功能。

    也就是说,值元组。现在这是一种基本类型,它使用字段来提高性能并减少复制。元组在 DTO 中占有一席之地,但当前的 System.Text.Json 无法处理它们。

    Work is already well under way for this,已经有一个 PR 正在审核,但目标版本是 5.0

    【讨论】:

      猜你喜欢
      • 2018-06-13
      • 2018-04-02
      • 1970-01-01
      • 1970-01-01
      • 2019-12-26
      • 1970-01-01
      • 1970-01-01
      • 2023-03-12
      • 2023-03-24
      相关资源
      最近更新 更多