C
C#4mo ago
SWEETPONY

✅ how to merge two objects?

Sometimes ago I had this object:
public sealed record CreateFlightLegModel
{
public string? Identity { get; init; }
public LegIdentityArgument? LegIdentity { get; init; }
public JsonDocument? LegData { get; set; }
}
public sealed record CreateFlightLegModel
{
public string? Identity { get; init; }
public LegIdentityArgument? LegIdentity { get; init; }
public JsonDocument? LegData { get; set; }
}
LegData used in method for merging and for example we can do this: var firstLeg =
JsonDocument.Parse(@"{
""fuel"":
{
""fuel_invoice_1"": ""1"",
""fuel_invoice_2"": ""2"",
""fuel_invoice_3"": ""3""
}
}");
JsonDocument.Parse(@"{
""fuel"":
{
""fuel_invoice_1"": ""1"",
""fuel_invoice_2"": ""2"",
""fuel_invoice_3"": ""3""
}
}");
var secondLeg=
JsonDocument.Parse(@"{
""fuel"":
{
""fuel_invoice_2"": null,
""fuel_invoice_3"": null
}
}");
JsonDocument.Parse(@"{
""fuel"":
{
""fuel_invoice_2"": null,
""fuel_invoice_3"": null
}
}");
and the output will be:
{
""fuel"":
{
""fuel_invoice_1"": ""1"",
""fuel_invoice_2"": null,
""fuel_invoice_3"": null
}
}
{
""fuel"":
{
""fuel_invoice_1"": ""1"",
""fuel_invoice_2"": null,
""fuel_invoice_3"": null
}
}
then we decided move from JsonDocument to model and this merge doesn't work anymore in case I pasted earlier output will be:
""fuel"":
{
""fuel_invoice_1"": null,
""fuel_invoice_2"": null,
""fuel_invoice_3"": null
}
""fuel"":
{
""fuel_invoice_1"": null,
""fuel_invoice_2"": null,
""fuel_invoice_3"": null
}
can someone understand me what to do?
4 Replies
Pobiega
Pobiega4mo ago
you will need to write the logic for merging two objects yourself, or use reflection (please dont)
SWEETPONY
SWEETPONY4mo ago
unfortunately I should use reflection :when:
Pobiega
Pobiega4mo ago
you really shouldnt. you could write a source generator that could generate a merge method thou that would be a much better option and provide the same "ease of use"
SWEETPONY
SWEETPONY4mo ago
I'm a little bit tired of sg because this LegData model also was generated by sg from json schema :catlaugh: This is why I can't write the logic for merging two objects, objects can be changed a little bit after nuget package update but.. maybe using sg for merge object is a good idea okay I will try it