Deserializing JSON

Kmcnet 886 Reputation points
2024-08-24T19:28:24.49+00:00

How do I deserialize json that starts with {"?xml":{"@version":"1.0","@encoding":"utf-8"}

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,736 questions
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 118.9K Reputation points
    2024-08-24T19:53:22.2166667+00:00

    For example:

    public class MyData
    {
        public string username { get; set; }
    }
    
    . . .
    
    string json = """
        {"?xml":{"@version":"1.0","@encoding":"utf-8"}, "username": "Sarah" }
        """;
    
    MyData my_data = System.Text.Json.JsonSerializer.Deserialize<MyData>( json );
    
    string username = my_data.username;
    

    If you need the unneeded values, then:

    public class MyData
    {
        [JsonPropertyName( "?xml" )]
        public Xml xml { get; set; }
    
        public string username { get; set; }
    }
    
    public class Xml
    {
        [JsonPropertyName( "@version" )]
        public string version { get; set; }
    
        [JsonPropertyName( "@encoding" )]
        public string encoding { get; set; }
    }
    
    . . .
    
    string json = """
        {"?xml":{"@version":"1.0","@encoding":"utf-8"}, "username": "Sarah" }
        """;
    
    MyData my_data = System.Text.Json.JsonSerializer.Deserialize<MyData>( json );
    
    string version = my_data.xml.version;
    string username = my_data.username;
    

1 additional answer

Sort by: Most helpful
  1. Michael Taylor 56,271 Reputation points
    2024-08-24T21:59:32.7033333+00:00

    What you're deserializing is an XML file converted to JSON. If you are calling an API that is doing that then it is bad. If you are calling an API and not setting Accept header as application/json then it might be returning XML to you instead. You would want to parse as XML, or request JSON for the format.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.