Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.Text.Json.JsonDocument.Parse array of objects

I am trying to parse below json using System.Text.Json.JsonDocument

[
    {
        "Name" : "Test 2",
        "NumberOfComponents" : 1,
        "IsActive" : true,
        "CreatedBy" : "bsharma"
    },
    {
        "Name" : "Test 2",
        "NumberOfComponents" : 1,
        "IsActive" : true,
        "CreatedBy" : "bsharma"
    }
]

The code to parse:

 using var jsonDoc = JsonDocument.Parse(inputStream, _jsonDocumentOptions);

The parsing fails with error:

System.Text.Json.JsonReaderException
  HResult=0x80131500
  Message='[' is an invalid start of a property name. Expected a '"'. LineNumber: 1 | BytePositionInLine: 4.
  Source=System.Text.Json
  StackTrace:
   at System.Text.Json.ThrowHelper.ThrowJsonReaderException(Utf8JsonReader& json, ExceptionResource resource, Byte nextByte, ReadOnlySpan`1 bytes)
   at System.Text.Json.Utf8JsonReader.ReadSingleSegment()
   at System.Text.Json.Utf8JsonReader.Read()
   at System.Text.Json.JsonDocument.Parse(ReadOnlySpan`1 utf8JsonSpan, Utf8JsonReader reader, MetadataDb& database, StackRowStack& stack)
   at System.Text.Json.JsonDocument.Parse(ReadOnlyMemory`1 utf8Json, JsonReaderOptions readerOptions, Byte[] extraRentedBytes)
   at System.Text.Json.JsonDocument.Parse(Stream utf8Json, JsonDocumentOptions options)

The json input is being sent in via an http request. The error message indicates to put the array in a property in form { "values" : [ .. ] }, which solves the problem. Is there a way to get a JsonDocument instance for the original json or the original json is invalid?

EDIT: The json comes from serializing an array:

    var jsonOptions = new JsonSerializerOptions
    {
        WriteIndented = true
    };

    var pocos = new Container[]
    {
        new Container { Name= "Test 2", NumberOfComponents = 2, IsActive = true ,CreatedBy = "bsharma" },
        new Container { Name= "Test 2", NumberOfComponents = 2, IsActive = true ,CreatedBy = "bsharma" }
    };
    var json = JsonSerializer.Serialize(pocos, jsonOptions);
like image 309
Brij Avatar asked Jul 10 '26 11:07

Brij


1 Answers

Try the new System.Text.Json APIs from .NET Blog show an example of this.

[
   {
       "date": "2013-01-07T00:00:00Z",
       "temp": 23,
   },
   {
       "date": "2013-01-08T00:00:00Z",
       "temp": 28,
   },
   {
       "date": "2013-01-14T00:00:00Z",
       "temp": 8,
   },
]

...

using (JsonDocument document = JsonDocument.Parse(json, options))
{
   int sumOfAllTemperatures = 0;
   int count = 0;

   foreach (JsonElement element in document.RootElement.EnumerateArray())
   {
       DateTimeOffset date = element.GetProperty("date").GetDateTimeOffset();
       (...)
like image 89
tymtam Avatar answered Jul 12 '26 02:07

tymtam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!