【问题标题】:Is there a Newtonsoft equivalent to the [XMLText] property using in xml serialization?是否有与在 xml 序列化中使用的 [XMLText] 属性等效的 Newtonsoft?
【发布时间】:2020-10-08 17:29:22
【问题描述】:

编辑:我意识到它可能是为上下文而导入的,我正在构建这个 JSON 以提高人类可读性(我认为以后没有业务需要将其解析回有意义的东西),这就是为什么我需要保持格式尽可能简单

所以我有一个要序列化为 JSON 的对象。序列化很复杂,我创建了一个辅助属性来处理它。每次匹配我希望它被序列化的方式时,helper 属性都会成功返回一个对象。不幸的是,序列化引擎仍然显示辅助函数名称,而不是仅仅将其输出视为我的对象状态的表示。

我正在寻找下面的输出

{
  "A" : <The output of the helper property>,
  "B" : <The output of the helper property>
}

但我实际上得到了

{
  "A" : {
    "HelperProperty": <The output of the helper property>
  },
  "B" : {
    "HelperProperty": <The output of the helper property>
  }
}

我知道在 XML 格式中有一个 [XMLText] 属性,我将其应用于“HelperProperty”属性来执行此操作。在 Newtonsoft 领域是否有类似的属性?或者,其他 Json 格式化程序是否支持这种类型的操作?


我现在拥有的 MVCE

我要序列化为 JSON 的对象

[JsonObject(MemberSerialization.OptIn)]
public class SerializationExample
{
    [JsonProperty]
    public object HelperProperty => (Object)A ?? (Object)B ?? (Object)C ?? "no property specified";

    public int? A;
    public string B;
    public Dictionary<String, int> C;
}

该对象的实例化及其序列化

var a = new SerializationExample() { A = 5 };
var b = new SerializationExample() { B = "five" };
var c = new SerializationExample() { C = new Dictionary<string, int>() { {"number" , 5 } } };

        
System.IO.File.WriteAllText(@"\users\sidney\desktop\output.json", 
    JsonConvert.SerializeObject(new Dictionary<string, SerializationExample>() {
        {"a",a },{"b",b },{"c",c } }, Formatting.Indented));

如何序列化

{
  "a": {
    "HelperProperty": 5
  },
  "b": {
    "HelperProperty": "five"
  },
  "c": {
    "HelperProperty": {
      "number": 5
    }
  }
}

我希望它如何序列化

{
  "a": 5,
  "b": "five",
  "c": {
    "number": 5
  }
}

【问题讨论】:

  • 你能告诉我们你用来序列化的类的结构吗?换句话说,您现在使用什么代码来达到输出?
  • @BrianRogers 我已经更新了该课程的 MVCE,以及​​我看到的行为以及我希望实现的目标。

标签: c# json serialization json.net


【解决方案1】:

虽然我找不到我想要的确切解决方案,但我发现您能够控制 json 的序列化方式,感谢 https://blog.maskalik.com/asp-net/json-net-implement-custom-serialization/

我所要做的就是定义一个类

public class DirectPropertySerializer : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var name = value as MyClass;
        serializer.Serialize(writer, name.HelperProperty);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }

    public override bool CanConvert(Type objectType)
    {
        return true;
    }
}

然后给MyClass添加一个属性

[JsonConverter(typeof(DirectPropertySerializer))]

(请注意,如上所述,我没有理由回读此 JSON 并尝试解析它,因此我只是将 ReadJson 函数保留为未实现。

【讨论】:

    猜你喜欢
    • 2021-12-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-16
    • 1970-01-01
    • 1970-01-01
    • 2014-05-28
    • 1970-01-01
    • 2020-03-03
    相关资源
    最近更新 更多