3

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?

8
  • Have you tried deserializing instead of trying to access the elements one by one? Eg JsonSerializer.Deserialize<Item[]>(json,options); Commented Oct 15, 2019 at 9:07
  • This does work, but I thought I could deserialize just until the point, where I find the correct element instead of deserializing my whole jsonstring. Commented Oct 15, 2019 at 9:16
  • JsonDocument.Parse parses the entire document too. Commented Oct 15, 2019 at 9:28
  • Is there a possiblity to circumevent this? Commented Oct 15, 2019 at 9:31
  • You can use Utf8JsonReader to read elements one by one, but that works with UTF8 sequences in the form of ReadOnlySpan<byte> and byte[]. You'll have to use varbytes=Encoding.UTF8.GetBytes(json);, or read directly from a UTF8 JSON file. What are you trying to do in the first place? System.Text.Json isn't a general-purpose JSON parser yet, it's meant for Web app serialization, where the payload is UTF8 and has to be parsed/deserialized entirely before it gets consumed. Commented Oct 15, 2019 at 9:40

2 Answers 2

1

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:

Sign up to request clarification or add additional context in comments.

Comments

0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.