从JSON数组字符串中删除第二项

时间:2020-05-11 09:04:32

标签: c# json

假设我有以下JSON

[{"ID": 1}, {"ID": 2}]

哪种是在不知道JSON对象类型的情况下删除第二项的最佳方法?

这就是我想要的:

[{"ID": 1}]

我尝试使用字符串操作,但我正在寻找更好的解决方案

2 个答案:

答案 0 :(得分:1)

string json = @"[{""ID"": 1}, {""ID"": 2}, {""ID"": 3}]"; 

var definition = new[] { new { ID = "" } };

var list = JsonConvert.DeserializeAnonymousType(json, definition).ToList();

if(list.Count >= 1)
    list.RemoveAt(1);

json = JsonConvert.SerializeObject(list); // Result : [{"ID":"1"},{"ID":"3"}]

答案 1 :(得分:0)

IMO,您应该使用名为string的库将JSONArray转换为Newtonsoft。这将使对字符串的操作更加容易,并使代码更易于维护和可读。

话虽如此,如果您必须使用String Manipulation进行操作,我建议您使用regex来匹配{}中的JSON对象元素,然后使用string.Replace()

下面是一段代码:

string input = "[{\"ID\": 1}, {\"ID\": 2}, {\"ID\": 3}]";
Regex regex = new Regex(@"\{(.*?)\}");
var matches = regex.Matches(input);

if (matches.Count < 2)
    throw new System.Exception("The content size must be at least two.");

// in case the collection only has 2 elements then there is no "," at the end.
string trailing = matches.Count > 2 ? "," : string.Empty;

var toRemove = matches.ElementAt(1).ToString() + trailing; 

input = input.Replace(toRemove, string.Empty);

System.Console.WriteLine(input); // prints out [{"ID": 1}, {"ID": 3}]
System.Console.ReadLine();