-2

Dear Community Members

Despite online searches, it is wondered how to efficiently index and retrieve corresponding values of a JsonElement Array using C#:

 string srep2 = " [ " + srep + " ] ";
 using JsonDocument doc = JsonDocument.Parse(srep2);
 var p = root[0]; // ValueKind = Object
 var a = p.GetProperty("resources"); //ValueKind = Array

Where p =

" [ {\"meta\":{\"collection_type\":\"json\",\"collection_total\":1},\"resources\":[{\"created_by\":\"ccccccc\",\"creation_date\":\"2021-12-10T14:02:53Z\",\"cd\":\"com\",\"description\":\"sample.\",\"uploaded\":true,\"id\":\"I\",\"labels\":[],\"last_update_date\":\"2021-12-10T14:02:53Z\",\"name\":\"TEST\",\"question\":{\"answer\":\"test-answer\",\"pseudo\":\"dv\"},\"key\":\"gk\",\"subject\":\"natural_science\",\"place\":2,\"state\":\"aj\",\"version\":[{\"auto\":false,\"created_by\":\"e2\",\"creation_date\":\"2021-12-10T14:02:53Z\",\"upload\":true,\"id\":\"sdsd\",\"available\":true}],\"total_vegetable\":1}]} ] "

And a =

  [{\"created_by\":\"ccccccc\",\"creation_date\":\"2021-12-10T14:02:53Z\",\"cd\":\"com\",\"description\":\"sample.\",\"uploaded\":true,\"id\":\"I\",\"labels\":[],\"last_update_date\":\"2021-12-10T14:02:53Z\",\"name\":\"TEST\",\"question\":{\"answer\":\"test-answer\",\"pseudo\":\"dv\"},\"key\":\"gk\",\"subject\":\"natural_science\",\"place\":2,\"state\":\"aj\",\"version\":[{\"auto\":false,\"created_by\":\"e2\",\"creation_date\":\"2021-12-10T14:02:53Z\",\"upload\":true,\"id\":\"sdsd\",\"available\":true}],\"total_vegetable\":1}]} ] "

Purposes:

(1) Indexing or finding the "name" property in Array [a]; (2) Retrieving its corresponding value: "TEST"

N.B: None of the combination performed independently has succeeded so far... hence this post.

Thanks in advance. Best

dbc
  • 104,963
  • 20
  • 228
  • 340
dark.vador
  • 619
  • 1
  • 6
  • 25
  • You are using [tag:system.text.json] not [tag:json.net]. If you want to access items inside a `JsonDocument` or `JsonElement` see [Getting nested properties with System.Text.Json](https://stackoverflow.com/a/61561343/3744182). Beyond that it's not clear exactly where your problem is, can you [edit] your question to share a [mcve]? – dbc Dec 19 '21 at 00:21

1 Answers1

0

you can put everything in one line

string name=string.Empty;

using (var doc  = JsonDocument.Parse(srep2) )
 name = doc.RootElement[0][0].GetProperty("resources")[0]
.GetProperty("name").ToString();

output

TEST
Serge
  • 40,935
  • 4
  • 18
  • 45