【问题标题】:How to change property/Attribute from JSON string in c#? [duplicate]如何从 C# 中的 JSON 字符串更改属性/属性? [复制]
【发布时间】:2016-05-20 14:52:04
【问题描述】:

我有类似的 JSON 字符串

{"name":"studentname","Lastname":"lastnameofstudent"}

我想将 name 属性/键更改为 FirstName 而不是此属性的值。使用 Newtonsoft JSON 库。

例子:

string json = @"{
  'name': 'SUSHIL'
}";
JObject obj = JObject.Parse(json);
var abc = obj["name"];
obj["name"] = "FirstName";
string result = obj.ToString();

【问题讨论】:

  • “我在 json 字符串中有密钥”不是很清楚你的意思。也不清楚您是要更改属性的 name 还是 valueminimal reproducible example 会更容易为您提供帮助。
  • 我想更改属性名称而不是它的值。
  • 因此,请使用该信息更新您的问题,并附上显示您尝试过的完整示例...
  • @PieroAlberto:这个问题是关于代码使用序列化类的情况。我在这里没有看到任何迹象。

标签: c# json.net


【解决方案1】:

最简单的方法可能只是分配一个新的属性值,然后为旧的调用Remove

using System;
using Newtonsoft.Json.Linq;

class Test
{
    static void Main()
    {
        string json = "{ 'name': 'SUSHIL' }";
        JObject obj = JObject.Parse(json);
        obj["FirstName"] = obj["name"];
        obj.Remove("name");
        Console.WriteLine(obj);
    }
}

输出:

{
  "FirstName": "SUSHIL"
}

【讨论】:

  • 感谢 Jon 得到了最终解决方案。我做错了 obj["name"] = "FirstName";任务。
猜你喜欢
  • 2023-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-03
相关资源
最近更新 更多