0

My JSON looks like this. Values can only be numeric, string or null:

attributes: {
    "value1": "name",
    "value2": 123,
    "value3": null
}

When deserializing, the values in the dictionary are deserialized as JsonElements.

Is there a way to always use simple types (double, string or null) instead? Do I need a custom converter?

Sample code:

using System;
using System.Collections.Generic;
using System.Text.Json;

public class Root 
{
    public IDictionary<string, object> attributes {get;set;} 
}
                    
public class Program
{
    
    public static void Main()
    {
        var json = "{\"attributes\":{\"value1\":\"something\",\"value2\":123}}";
        var o = JsonSerializer.Deserialize<Root>(json);
        
        Console.WriteLine(o.attributes["value1"].GetType()); 
        // prints: System.Text.Json.JsonElement     
    }
}


1 Answer 1

-1

Have you tried below:

  1. Convert your data to JsonNode first
  2. and then on JsonNode, you can do .GetValue<YOUR_TYPED_CLASS_HERE>();
Sign up to request clarification or add additional context in comments.

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.