【发布时间】:2021-10-22 11:39:06
【问题描述】:
假设我有一些我经常序列化的类,例如
public class A
{
public A(int x, bool y)
{
X = x;
Y = y;
}
[JsonProperty("x_thing")]
public int X { get; }
[JsonProperty("y_thing")]
public bool Y { get; }
}
public class B
{
public B(string s)
{
S = s;
}
[JsonProperty("string_thing")]
public string S { get; }
}
如果我想从这里开始(但假装A 和B 是任意对象):
var obj1 = new A(4, true);
var obj2 = new B("hello world");
...那我怎样才能习惯性地生成这个 JSON 序列化呢?
{
"x_thing": 4,
"y_thing": true,
"string_thing": "hello world"
}
【问题讨论】:
-
您想将它们合并为字符串吗?
-
@gunr2171 唯一的通用解决方案是编写自己的转换器,我简直不敢相信这是最好的方法
-
@Heinzi 好主意,但我宁愿在序列化之前将每个对象转换为中间对象 - 似乎效率更高......目前正在研究 Json.NET 的 Linq.JObject
-
@AndriyShevchenko 我的意思是,我认为我必然需要将它们合并为抽象对象......?
标签: c# .net-core reflection json.net