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);
}
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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.