C#如何使用system.text.json在动态JSON对象中更改单个值?

发布于 2025-02-13 06:06:15 字数 975 浏览 1 评论 0原文

我有一个看起来像这样的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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

弥枳 2025-02-20 06:06:17

尝试一下

    string json = File.ReadAllText(filepath);

    var settings  = JsonNode.Parse(json); 
    settings ["url"]= "new url";
    json=settings.ToJsonString(new JsonSerializerOptions { WriteIndented = true });

    File.WriteAllText(filepath, json);

try this

    string json = File.ReadAllText(filepath);

    var settings  = JsonNode.Parse(json); 
    settings ["url"]= "new url";
    json=settings.ToJsonString(new JsonSerializerOptions { WriteIndented = true });

    File.WriteAllText(filepath, json);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文