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

Time:03-17

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.

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?

CodePudding user response:

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; }
}
  • Related