System Text Json read single object from array of objects

Viewed 7293

I'm trying to use the new System Text Json Library to read a single object from my json array. My json looks like this:

[
  {
    "Id": "test1",
    "Version": "16.0.461",
  },
  {
    "Id": "test2",
    "Version": "2.1.0",
  }
]

This is just an example. One Json Object actually has around 12 propteries. But suppose there is an class in c#, which looks like this:

     public class Data
     {
            public string Id { set; get; }
            public string Version { set; get; }
     }

and I'd like to just get the package where the id matches the given namen, which I tried like this:

    private static ObjectData GetSingleData(string jsonString, string objectName)
    {
                var options = new JsonDocumentOptions
                {
                    AllowTrailingCommas = true
                };

                using (JsonDocument document = JsonDocument.Parse(jsonString, options))
                {
                    ArrayEnumerator arrayEnumerator = document.RootElement.EnumerateArray();
                    //ObjectEnumerator objectEnumerator1 = document.RootElement.EnumerateObject();
                    while (arrayEnumerator.MoveNext())
                    {
                        JsonElement current = arrayEnumerator.Current;
                        if (objectName.Equals(current.GetProperty("id"))) 
                        {
                            //here the conversion from current to object should happen, but I don't know how                      
                        }
                    }
                }

                return null;
     }

is there a possiblity to convert a JsonElement to a instance of my Data Class?

2 Answers

Use something like this:

JsonElement current = document.RootElement;  
if (objectName.Equals(current.GetProperty("Id"))) 
{
     //But i'm using TryGetProperty
     //This is example code for first element in JSON array
     string id = current[0].GetProperty("Id").GetString(); //test1
     string version = current[0].GetProperty("Version").GetString(); //16.0.461
     
     //And now you can create your Data object
     Data data_object = new Data(id, version)
}

If I understand you correctly this should work.

UPD: I don't recommend that you use the standard library, so use Json.NET instead , this library is very convenient and works faster (for example, I achieved deserialization speed to ~0.2 seconds link for more info)

UPD 2:
For .NET 5:

.NET 6 has JsonElement.Deserialize<T>(). (source)

var obj = current.Deserialize<ObjectData>();
Related