System.Text.Json.JsonDocument.Parse 对象数组

Bri*_*rij 5 c# json .net-core asp.net-core system.text.json

我正在尝试使用以下 json 进行解析System.Text.Json.JsonDocument

[
    {
        "Name" : "Test 2",
        "NumberOfComponents" : 1,
        "IsActive" : true,
        "CreatedBy" : "bsharma"
    },
    {
        "Name" : "Test 2",
        "NumberOfComponents" : 1,
        "IsActive" : true,
        "CreatedBy" : "bsharma"
    }
]
Run Code Online (Sandbox Code Playgroud)

要解析的代码:

 using var jsonDoc = JsonDocument.Parse(inputStream, _jsonDocumentOptions);
Run Code Online (Sandbox Code Playgroud)

解析失败并出现错误:

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)
Run Code Online (Sandbox Code Playgroud)

json 输入通过 http 请求发送。错误信息表明将数组放入 form 的属性中{ "values" : [ .. ] },即可解决问题。有没有办法获取原始json的JsonDocument实例或者原始json无效?

编辑:json 来自序列化数组:

    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);
Run Code Online (Sandbox Code Playgroud)

tym*_*tam 12

尝试 .NET 博客中的新 System.Text.Json API,其中展示了一个示例。

[
   {
       "date": "2013-01-07T00:00:00Z",
       "temp": 23,
   },
   {
       "date": "2013-01-08T00:00:00Z",
       "temp": 28,
   },
   {
       "date": "2013-01-14T00:00:00Z",
       "temp": 8,
   },
]
Run Code Online (Sandbox Code Playgroud)

...

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();
       (...)
Run Code Online (Sandbox Code Playgroud)


hal*_*ldo 5

.NET 6添加了新的命名空间System.Text.Json.NodesJArray ,它允许以与 Newtonsoft.Json和类似的方式随机访问 Json 值JObject

您可以使用JsonNode.Parse()将 Json 从流(或字符串或 JsonReader)解析为JsonArray.

// parse from stream, string, utf8JsonReader
JsonArray? array = JsonNode.Parse(stream)?.AsArray();

// access values
string name = array[0]["Name"].ToString();
int number = (int) item["NumberOfComponents"];

// or iterate
foreach (var item in array)
{
    string name = item["Name"].ToString();
    int componentCount = (int) item["NumberOfComponents"];
    bool isActive = (bool) item["IsActive"];

    Console.WriteLine($"Name:{name}, #comps:{componentCount}, Active:{isActive}");
}

// serialize
var jsonString = array.ToJsonString();

// deserialize to defined class
List<Item> items = array.Deserialize<List<Item>>();
Run Code Online (Sandbox Code Playgroud)

如果您只想快速访问或修改 Json,则添加JsonObject,JsonArrayJsonNode会使 System.Text.Json 中的 Json 处理变得更加容易。

另请参阅我对Equivalent of JObject in System.Text.Json 的回答,了解有关 的详细信息JsonObject


Dmi*_*try 2

原始 JSON 无效。

检查https://www.json.org/json-en.html上的 json 语法

当然,您可以手动修剪 json 字符串中的第一个/最后一个大括号,然后将其余部分解析为数组,但这与问题中的“原始 json 的 JsonDocument 实例”不一致。

  • 我不明白投反对票,因为最后的问题是:“有没有办法获取原始 json 的 JsonDocument 实例,或者原始 json 无效?”,这个答案正确地指出 json 位于事实无效。 (3认同)