【问题标题】:C# JSON.NET remove strings with ","C# JSON.NET 使用“,”删除字符串
【发布时间】:2016-09-10 19:12:03
【问题描述】:

我对 json.net 的最后一个问题:

我的文件包含其中一些人:

{
      "type": "06A, 06B, 06C, 06D, 06E",
      "qt": "6-8-",
      "id": "06A, 06B, 06C, 06D, 06E6-8-"
    }

现在我想清理我的文件并删除类型包含逗号或“,”的所有对象。

我已经读过这个:C# remove json child node using newtonsoft 但是如果它包含一个特殊的字符,就不可能删除它...

非常感谢任何帮助!

目前我有:

public void filter()
    {
        string sourcePath = @Settings.Default.folder;
        string pathToSourceFile = Path.Combine(sourcePath, "file.json");

        string list = File.ReadAllText(pathToSourceFile);
        Temp temporaray = JsonConvert.DeserializeObject<Temp>(list);

    }

【问题讨论】:

  • 你所说的blocks是什么意思?预期的输出 json 是什么?到目前为止,您尝试过什么?
  • 对不起,“块”是指包含类型、qt 和 id 的整个对象
  • 反序列化为对象并使用Where过滤。然后你可以根据需要重新序列化为 json。
  • @SimpleVar 现在我添加了一些代码,如何使用“Where”进行过滤?

标签: c# json json.net


【解决方案1】:

您可以使用 LINQ to JSON 解析 JSON 并删除包含与您的条件匹配的 "type" 属性的对象,而不是反序列化为临时的 Temp 类型:

var root = JToken.Parse(json);

if (root is JContainer)
{
    // If the root token is an array or object (not a primitive)
    var query = from obj in ((JContainer)root).Descendants().OfType<JObject>()  // Iterate through all JSON objects 
                let type = obj["type"] as JValue                                // get the value of the property "type"
                where type != null && type.Type == JTokenType.String 
                    && ((string)type).Contains(",")                             // If the value is a string that contains a comma
                select obj;                                                     // Select the object
    foreach (var obj in query.ToList())
    {
        // Remove the selected object
        obj.Remove();
    }
}

示例fiddle

然后要序列化成一个名为fileName的文件,可以序列化root对象,如Serialize JSON to a file所示:

using (var file = File.CreateText(fileName))
{
    var serializer = JsonSerializer.CreateDefault(new JsonSerializerSettings { Formatting = Formatting.Indented });
    serializer.Serialize(file, root);
}

【讨论】:

  • 好的,我必须如何在 obj.Remove(); 之后继续?字符串 gesamt = JsonConvert.SerializeObject(obj, Formatting.Indented); File.WriteAllText(@Settings.Default.folder + "\\" + "上传" + "\\" + "ee.json", gesamt);不会工作...
  • @Francis 试试root 对象。很好的答案,我唯一要改变的是.ToArray(),而不是“更快的迭代ninini”列表
  • @Francis - 你是什么意思它不起作用?您是在问,如何将字符串写入文件? 还是在问,如何使用 Json.NET 将对象序列化为文件? 如果是后者,见newtonsoft.com/json/help/html/…
猜你喜欢
  • 2012-06-17
  • 2013-09-30
  • 2022-01-09
  • 2011-12-10
  • 1970-01-01
  • 1970-01-01
  • 2018-01-16
相关资源
最近更新 更多