Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Deserialize JSON with special characters in property name

I have a json property like "A\/B" and I want to deserialize it in c# property AB

I have tried both System.Text.Json and

[JsonPropertyName(@"A\/B")]
public bool AB { get; set; }

Or

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[JsonProperty(@"A\/B")]
public bool AB { get; set; }

Or

[JsonProperty(PropertyName = (@"A\/B")]
public bool AB { get; set; }

or

[JsonPropertyName("A\\/B")]
public bool? AB { get; set; }

but is not deserialized correctly is always false and in the json file is true like "A/B": true,.

Json example :

{
    "List": [
        {
            "Name": "name",
            "A\/B": true,
        },
        {
            "Name": "name1",
            "A\/B": false,
        }
    ]
        
}

Any suggestions will be highly appreciated.

>Solution :

If the JSON looks like

{
    "A\/B": true
}

Then the name of the property is actually just A/B.

The backslash character also acts as an escape character in JSON syntax, so the backslash isn’t actually part of the property name. Even though the forward slash doesn’t need any escaping in this case, it is still acceptable to escape it nonetheless. See RFC 8259 section 7.

So, in your C# code, you also don’t need any backslashes:

[JsonProperty("A/B")]

or

[JsonPropertyName("A/B")]

depending on whether you are using Json.NET or System.Text.Json.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading