C#JSON.NET使用“,"删除字符串. [英] C# JSON.NET remove strings with ","

查看:134
本文介绍了C#JSON.NET使用“,"删除字符串.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

My last question to json.net:

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

My file contains some of those guys here:

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

现在,我要清除文件并删除所有类型包含逗号或,"的对象.

Now I want to clean my file and remove all objects where the type contains a comma or ",".

我已经读过这篇文章: C#使用newtonsoft删除json子节点,但是如果对象包含特殊字符,则无法删除它.

I already read this: C# remove json child node using newtonsoft but there is no possibility to remove the object if it contains a special char...

我将非常感谢您的帮助!

I would really appreciate any help!

目前,我有:

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);

    }

推荐答案

您可以使用属性的对象:

Rather than deserializing to a temporary Temp type, you can use LINQ to JSON to parse the JSON and remove objects containing a "type" property matching your criterion:

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();
    }
}

示例小提琴.

然后要序列化为名称为fileName的文件,可以序列化root对象,如

Then to serialize to a file with name fileName, you can serialize the root object as shown in Serialize JSON to a file:

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

这篇关于C#JSON.NET使用“,"删除字符串.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆