Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CSHARP

system.text.json ways to go about getting to the data how to get the data text.json you should use JsonDocument when

///<Summary>
/// You should use JsonDocument and its related types when:
///
/// The JSON would be too complex to represent in a POCO.
/// You need access to only a few specific parts of the JSON data.
/// You don’t know the format of the JSON or the JSON could have multiple formats.
///</Summary>


// There are two ways to go about getting to the data that interests you. The first, if you know what you’re looking for,
// is to access the element directly through the DOM. You could for example do the following to get a known property:

// {"Topic":"Json Serialization Part 1","Part":1,"Author":"Marc","Co-Author":"Helen","Keywords":["json","netcore","parsing"]}
var blogPost = JsonDocument.Parse(stringifiedJson);
var topic = blogPost.RootElement.GetProperty("Topic").GetString();

//That works great for random access to a property that you know how to find. But what if you’re looking for a property that could be anywhere in the document? Or you need to read a particular property from each object in a JSON array? That’s where EnumerateObject and EnumerateArray come in. They can be used together to walk through any JsonDocument:


// {"Topic":"Json Serialization Part 1","Part":1,"Author":"Marc","Co-Author":"Helen","Keywords":["json","netcore","parsing"]}
var blogPost = JsonDocument.Parse(stringifiedJson);
 
// Find all authors, returns enumerable with "Marc", "Helen"
var authors = blogPost.RootElement.EnumerateObject()
                   .Where(it => it.Name.Contains("Author") && it.Value.ValueKind == JsonValueKind.String);
 
// Find all keywords, returns enumerable with "json", "netcore", "parsing"
var keywords = blogPost.RootElement.EnumerateObject()
                  .Where(it => it.Value.ValueKind == JsonValueKind.Array && it.Name == "Keywords")
                  .SelectMany(it => it.Value.EnumerateArray().Select(that => that.GetString()));

// Serialization and deserialization are both expensive operations. The JsonDocument API is designed to keep allocations down a minimum, reducing the impact it has on your application.
Source by marcroussy.com #
 
PREVIOUS NEXT
Tagged: #ways #data #data #JsonDocument
ADD COMMENT
Topic
Name
5+9 =