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

Can System.Text.Json be used to decode and parse an encoded JSON string?

I have some incoming text that is encoded JSON.

{\"field1\":\"value1\",\"field2\":\"value2\"}

When I try to parse that with JsonDocument.Parse(text) I get an error complaining about the \ character.

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

I tried…

var options = new JsonSerializerOptions
{
   Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
};

var obj = JsonDocument.Parse(text, options);

…but that did not help.

I’m missing a step here. I was thinking about just stripping out the \ first, but if a decoder is available that will be preferable.

Is there an option or method built into the System.Text.Json namespace that I can use to prepare that string before I attempt to parse it?

>Solution :

you don’t need any options

    var json="{\"field1\":\"value1\",\"field2\":\"value2\"}";

    var obj = JsonDocument.Parse(json);

result

{
  "field1": "value1",
  "field2": "value2"
}

or if you need to deserialize

Data data= System.Text.Json.JsonSerializer.Deserialize<Data>(json);

public partial class Data
{
    [JsonProperty("field1")]
    public string Field1 { get; set; }

    [JsonProperty("field2")]
    public string Field2 { get; set; }
}
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