C# JSON.NET remove strings with “,”

可紊 提交于 2019-12-13 09:48:23

问题


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 ",".

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!

At the moment I have:

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

    }

回答1:


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

Sample fiddle.

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


来源:https://stackoverflow.com/questions/39429681/c-sharp-json-net-remove-strings-with

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!