gpt4 book ai didi

c# - JSON 补丁更新嵌套对象

转载 作者:行者123 更新时间:2023-12-04 12:16:12 27 4
gpt4 key购买 nike

我一直在尝试使用 JSON Patch 在嵌套对象中使用替换值,但是我觉得我没有得到正确的符号。任何想法应该是什么路径?
我在 LINQPad 6 中创建了以下代码来证明它.

void Main()
{
var patchTest = new PatchTest();
patchTest.Create();
patchTest.ToString().Dump("Before Patch");
var patch = JsonConvert.DeserializeObject<JsonPatchDocument<Contact>>(
@"[
{
""op"": ""replace"",
""path"": ""/firstname"",
""value"": ""Benjamin""
},
{
""op"": ""replace"",
""path"": ""age"",
""value"": ""29""
},
{
""op"": ""replace"",
""path"": ""//Appointment//Name"",
""value"": ""fsdfdsf""
},
]");
patchTest.Patch(patch);
patchTest.ToString().Dump("After Patch");
}

public class PatchTest
{
public Contact Contact { get; set; }

public PatchTest() { }

public void Create()
{
Contact = new Contact
{
FirstName = "Walt",
LastName = "Banks",
Age = 20
};
}

public void Patch(JsonPatchDocument<Contact> patch)
{
patch.Replace(e => e.Appointment, Contact.Appointment);
patch.ApplyTo(Contact);
}

public override string ToString()
{
return $"{nameof(Contact)}: {Contact}";
}
}

public class Contact
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public Appointment Appointment { get; set; }

public override string ToString()
{
return $"{nameof(FirstName)}: {FirstName}, {nameof(LastName)}: {LastName}, {nameof(Appointment)}: {Appointment}";
}
}


public class Appointment
{
public string Name { get; set; }

public override string ToString()
{
return $"{nameof(Name)}: {Name}";
}
}
但是它找不到名称
enter image description here

最佳答案

找不到约会名称的原因是你没有初始化Appointment创建您的 Contact 时.更改 Create到:

public void Create()
{
Contact = new Contact
{
FirstName = "Walt",
LastName = "Banks",
Age = 20,
Appointment = new Appointment()
};
}
在控制台应用程序中运行您的示例现在会产生以下输出:
Before Patch
Contact: FirstName: Walt, LastName: Banks, Age: 20, Appointment: Name:
After Patch
Contact: FirstName: Benjamin, LastName: Banks, Age: 29, Appointment: Name: fsdfdsf
我加了 Contact.Age到其 ToString()覆盖,因为它丢失了。还有,单例 /和双 //两者都在路径中工作。我猜你在试图找出问题时使用了后者。
现在,由于您已经在 J​​SON 中定义了文档,因此不需要定义另一个替换操作。您的 Patch方法可以简化为:
public void Patch(JsonPatchDocument<Contact> patch)
{
patch.ApplyTo(Contact);
}
并且输出将与以前相同。等价于在代码中完成所有这些,无需手动创建 JSON 文档,如下所示:
public void Patch(Contact amendedContact)
{
var patch = new JsonPatchDocument<Contact>();
patch.Replace(e => e.FirstName, amendedContact.FirstName);
patch.Replace(e => e.Age, amendedContact.Age);
patch.Replace(e => e.Appointment.Name, amendedContact.Appointment.Name);
patch.ApplyTo(Contact);
}
并像这样调用它:
var amendedContact = new Contact
{
FirstName = "Benjamin",
Age = 29,
Appointment = new Appointment
{
Name = "fsdfdsf"
}
};

patchTest.Patch(amendedContact);
这再次产生您想要的输出。但是您仍然必须确保初始化嵌套属性,否则您将遇到原始问题。

关于c# - JSON 补丁更新嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64048234/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com