【问题标题】:C# Object Serialized using Newton.JSON is Empty [duplicate]使用 Newton.JSON 序列化的 C# 对象为空 [重复]
【发布时间】:2019-10-14 11:01:06
【问题描述】:

我在使用 Newton.Json 序列化对象时遇到问题,当我使用断点进行调试时,我发现我的序列化对象是空的,而提供给序列化程序的对象是完整的。

我已附上屏幕截图。

编辑: 这是我要序列化其列表的类。

class ArgumentGroup
{
    String argumentGroupName = "";
    String argumentDescription = "";
    int argumentCount = 0;
    List<Argument> argumentList = new List<Argument>();

    public ArgumentGroup(string argumentGroupName, string argumentDescription, int argumentCount, List<Argument> argumentList)
    {
        this.argumentGroupName = argumentGroupName;
        this.argumentDescription = argumentDescription;
        this.argumentCount = argumentCount;
        this.argumentList = argumentList;
    }
}

【问题讨论】:

  • 你能告诉我们你正在序列化的类吗?
  • @EylM 我已经用代码 sn-p 更新了。
  • 添加这个:var obj = new ExampleClass(); var jsons = JsonConvert.SerializeObject(obj, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore });
  • 此对象中没有要序列化的公共属性
  • 使用公共属性,而不是字段。字段是实现细节,只有 properties 是类接口的一部分。序列化程序(全部)使用属性。它们也可以配置为使用字段,甚至是私有字段,但它们不应该除非有非常重要的原因

标签: c# serialization json.net


【解决方案1】:

公开您的字段,因为默认 NewtonSoft.Json 只会序列化公共成员或 出于某种原因你真的不想公开你的字段,你可以使用 JsonPropertyAttribute 来允许它们被序列化和反序列化。

【讨论】:

  • 公共字段是个坏主意——字段是实现细节。序列化器旨在序列化 properties.
  • 是的,这就是为什么添加“或出于某种原因您真的不想公开您的字段,您可以使用 JsonPropertyAttribute 来允许它们被序列化和反序列化。”
  • @PanagiotisKanavos 我同意公共字段是个坏主意,但它使它们出现在 json 中。
【解决方案2】:

JsonProperty 有每个类的属性吗?

[JsonProperty("argumentGroupName")]
public string argumentGroupName { get; set; }

并导入:

using System;
using System.Collections.Generic;

using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

【讨论】:

  • JsonPropert没有理由,JSON.NET默认序列化所有属性
  • JSON.NET 默认只序列化公共属性,而不是所有属性!!!!
  • 您使用了公共属性,这意味着不需要JsonProperty
猜你喜欢
  • 1970-01-01
  • 2019-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多