-3

I want to use System.Text.Json instead of Newtonsoft.Json. But, I was unable to convert the string to an object.

Here is my request:

{"Abc":'{"Property1":"abds","property2":"232"}'}

I've tried to parse this string by JsonSerializer.Deserialize<A>(request) and I'm getting an error.

Please suggest to me how can I parse this string into an object?

Thanks in advance!

Timothy G.
  • 6,335
  • 7
  • 30
  • 46
prasanthi
  • 562
  • 1
  • 9
  • 25
  • What code have you written and what error do you get? – David Sep 02 '21 at 11:19
  • Please show us your code and what have you done. Without these details, we could not help you further and your question may risk to be closed by others. – Eriawan Kusumawardhono Sep 02 '21 at 11:21
  • You should explain your problem more further and with more code, that way community can give you better answer. – I.Step Sep 02 '21 at 11:51
  • Your JSON is malformed. Upload it to https://jsonlint.com/ and you will get an error. The problem is that the value `'{"Property1":"abds","property2":"232"}'` of `"Abc"` is surrounded in single quotes, and single quotes are not valid string delimiters as per the [JSON Standard](https://www.json.org/json-en.html). Json.NET is forgiving and parses them anyway but System.Text.Json does not. See [System.Text.Json disallows string literals surrounded by single quotes #31608](https://github.com/dotnet/runtime/issues/31608). – dbc Sep 02 '21 at 15:58

1 Answers1

2

First of all your json string is invalid because of single quotes, remove the single quote, create classes as follows

    public class Abc
    {
        public string Property1 { get; set; }
        public string property2 { get; set; }
    }

    public class Root
    {
        public Abc Abc { get; set; }
    }

and then deserialize like : JsonSerializer.Deserialize<Root>(jsonString);

Sarang Kulkarni
  • 367
  • 2
  • 6
  • 1
    Is the entire object invalid JSON? Or is the entire object a normal JavaScript object which contains a single property called `Abc` whose *value* is a perfectly valid JSON string? The question is unclear about this. – David Sep 02 '21 at 11:27
  • if you parse json you ll get `SyntaxError: Unexpected token ' in JSON at position 7` – Sarang Kulkarni Sep 02 '21 at 12:28