2016-09-10 69 views
-3

我最后的问题JSON.NET:C#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); 

    } 
+0

你是什么*块意味着*?什么是预期的输出json?你试过什么了? –

+0

对不起,“块”我的意思是整个对象包含类型,qt和id – Francis

+2

反序列化成对象并用'Where'过滤。然后你可以重新序列化为json,如果你需要的话。 – SimpleVar

回答

2

而不是反序列化到一个临时Temp类型,你可以使用LINQ to JSON解析JSON并删除含有"type"财产符合条件的对象:

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

没关系,我该如何继续obj.Remove(); ? string gesamt = JsonConvert.SerializeObject(obj,Formatting.Indented); File.WriteAllText(@ Settings.Default.folder +“\\”+“upload”+“\\”+“ee.json”,gesamt);没有工作... – Francis

+1

@Francis尝试'root'对象。很好的答案,我只会改变'.ToArray()'而不是列表中的“更快迭代ninini” – SimpleVar

+0

@Francis - 你是什么意思**它不工作**?你问,*我怎样才能写一个字符串到一个文件?*或者你问,*我如何用Json.NET序列化一个对象到一个文件?*如果后者,请参阅http://www.newtonsoft。 COM/JSON /帮助/ HTML/SerializeWithJsonSerializerToFile.htm。 – dbc