假設我有一些我經常正常序列化的類,例如
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"
}
uj5u.com熱心網友回復:
JObject有一個合并方法:
var json1 = JObject.FromObject(obj1);
var json2 = JObject.FromObject(obj2);
json1.Merge(json2);
// json1 now contains the desired result
小提琴
如果您的物件包含具有相同名稱的屬性,您可以使用采用JsonMergeSettings物件的多載來指定應如何解決沖突。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/331410.html
上一篇:希望我的while回圈在我輸入一個超過800的數字后完成并輸出,但它給了我未處理的例外
下一篇:我應該有多少個模型類?
