C#如何使用system.text.json在动态JSON对象中更改单个值?
我有一个看起来像这样的JSON文件:
{
"a":{
"lot":"of",
"random":"stuff"
},
"url":"https://a.url.I.want.to.change",
"some":{
"other":"very",
"random":"stuff"
}
}
我从文件中读取了JSON,我想精确更改url
字段,而不是要将其保存回文件。
我在整个项目中使用system.text.json
,我不想将依赖项引入newtonsoft.json
我使用dynamic
代码>像这样:
string json = File.ReadAllText(filepath);
dynamic settings = JsonSerializer.Deserialize<dynamic>(json);
settings.url = "https://my.new.url"; // <- that is the problem
File.WriteAllText(filepath, JsonSerializer.Serialize(settings));
也这样:
settings["url"] = "https://my.new.url";
但是,这些方法都没有起作用,因为jsonserializer
将其归为jsonelement
,这是我认为的。
有人对如何解决这一想法吗?
I have a json file that looks something like this:
{
"a":{
"lot":"of",
"random":"stuff"
},
"url":"https://a.url.I.want.to.change",
"some":{
"other":"very",
"random":"stuff"
}
}
I read that json from a file and I want to change exactly the url
field and than I want to save it back to the file.
I am using System.Text.Json
in the entire project and I don´t want to introduce a dependency to newtonsoft.json
I tried it using dynamic
like this:
string json = File.ReadAllText(filepath);
dynamic settings = JsonSerializer.Deserialize<dynamic>(json);
settings.url = "https://my.new.url"; // <- that is the problem
File.WriteAllText(filepath, JsonSerializer.Serialize(settings));
and also like this:
settings["url"] = "https://my.new.url";
but none of the approaches work because JsonSerializer
deserializes it into an JsonElement
, which is readonly I think.
Has anyone an idea of how that could be solved?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试一下
try this