如何更改 JSON 的列表(或数组)类型的值?

How to change JSON's value for List (or array) type?

"title" : { "newTitle" : "Test"}
"tags" : { "newTags" : ["Tag1", "Tag2"] }
Newtonsoft.Json.Linq;

var json = JObject.Parse(json: json);
var title;  // "Test2" in title
List<string> tags; // "TagA", "TagB", "TagC" in tags


json["title"]["newTitle"] = title; // works well
json["tags"]["newTags"] = tags; // not work

我想要 JSON 结果如下:

"title" : { "newTitle" : "Test2"}
"tags" : { "newTags" : ["TagA", "TagB", "TagC"] }

我想修改JSON的一些值。 intstring 效果很好。但是,ListArray 不起作用。

请多多指教

我用了翻译器。所以写的可能比较别扭

假设您的 JSON 数据已经定义了对象模板,您可以根据您的 JSON 数据创建一个 class。使用 Newtonsoft.Json,您将 JSON 反序列化为一个对象,然后更新该对象的属性值。

注意:当访问对象的内部属性时,例如Title.NewTitleTags.NewTags,您可能需要添加一些空检查以防止NullReferenceException

第一个解决方案:转换为强类型对象

public static void Main()
{
    var json = "{\"title\" : { \"newTitle\" : \"Test\"}, \"tags\" : { \"newTags\" : [\"Tag1\", \"Tag2\"] }}";
        
    var inputObj = JsonConvert.DeserializeObject<JsonInput>(json);
    inputObj.Title.NewTitle = "Test2";
    inputObj.Tags.NewTags = new List<string> {"TagA", "TagB", "TagC"};
        
    Console.WriteLine(JsonConvert.SerializeObject(inputObj));
}

public class JsonInput
{
    public Title Title {get;set;}
    public Tags Tags {get;set;}
}

public class Title
{
    public string NewTitle {get;set;}
}

public class Tags
{
    public List<string> NewTags {get;set;}
}

1st solution Code snippets and Output

第二种解决方案:使用动态

要更新数组,您需要将 List<string> 解析为 JArray 类型

public static void Main()
{
    var json = "{\"title\" : { \"newTitle\" : \"Test\"}, \"tags\" : { \"newTags\" : [\"Tag1\", \"Tag2\"] }}";
        
    var title = "Test2";  // "Test2" in title
    List<string> tags = new List<string> {"TagA", "TagB", "TagC"}; // "TagA", "TagB", "TagC" in tags

    dynamic root = JObject.Parse(json);
    JObject titleObj = (JObject)root["title"];
    titleObj["newTitle"] = title;
        
    JObject tagsObj = (JObject)root["tags"];
    tagsObj["newTags"] = JArray.FromObject(tags);
        
    Console.WriteLine(root);
}

2nd solution Code snippets and Output

试试这个

     var jsonObject=JObject.Parse(json);

    var newTitle =   "Test2";
    List<string> newTags = new List<string> { "TagA", "TagB", "TagC"};
    
    jsonObject["title"]["newTitle"]= newTitle; 
    jsonObject["tags"]["newTags"]= JArray.FromObject(newTags);

结果

{
  "title": {
    "newTitle": "Test2"
  },
  "tags": {
    "newTags": [
      "TagA",
      "TagB",
      "TagC"
    ]
  }
}