Search code examples
c#jsonfindall

JSon Find multiple specific Values multiple times in C#


I want to search or iterate a pretty huge JSon and find 3 key-value pairs every time they appear. Is there any method or function that could help me doing that? Or is it even possible?

I need to find the first value and from that point on the second, afterwards the third and then the first again. I know there is FindAll for strings, but it's not that nice to handle a JSon as a string.

Edit: I am using C#


Solution

  • If your data is massive then I'd recommend streaming the content in and processing it.

    For this you can use JsonTextReader - https://www.newtonsoft.com/json/help/html/ReadJsonWithJsonTextReader.htm

        var filePath = Path.GetTempFileName();
    
        File.WriteAllText(filePath, "{bigJson: true}");
    
        var stream = File.Open(filePath, FileMode.Open);
    
        JsonTextReader reader = new JsonTextReader(new StreamReader(stream));
        while (reader.Read())
        {
            if (reader.Value != null)
            {
                Console.WriteLine("Token: {0}, Value: {1}", reader.TokenType, reader.Value);
            }
            else
            {
                Console.WriteLine("Token: {0}", reader.TokenType);
            }
        }