【发布时间】: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