-3

I've got the string value :

var jsonStringValue= "[{\"id\": \"001\",\"schoolName\": \"Johnson Primary School\",\"rules\": \"[{\\\"key\\\":\\\"bc92f\\\",\\\"student\\\":\\\"peter\\\",\\\"class\\\":\\\"6A\\\"},{\\\"key\\\":\\\"c929\\\",\\\"student\\\":null,\\\"class\\\":null}]\"}]"

and I want to expect to produce the JsonObject or dynamic object as below

[
    {
        "id": "001",
        "schoolName": "Johnson Primary School",
        "rules": [
            {
                "key": "bc92f",
                "student": "peter",
                "class": "6A"
            },
            {
                "key": "c929",
                "student": null,
                "class": null
            }
        ]
    }
]

But I cannot do it in this code :

var jsonObject = System.Text.Json.JsonSerializer.Deserialize<JsonObject>(jsonStringValue);

because the rules inside contain slash or sometime it have \r\n can I know how to convert it by using System.Text.Json.JsonSerializer in dotnet 6?

Thank you

Carrie Kaski
  • 133
  • 7
  • 1
    Your first code block is not valid C# because the double quotes that you want inside the string are not escaped. – gunr2171 Sep 28 '22 at 15:37
  • 1
    In addition, it's going to be hard to produce a JsonObject if your Json is an _array_. Why do you want to deserializeto this type? What are you trying to accomplish? – gunr2171 Sep 28 '22 at 15:39
  • Because, I need to convert it into object and check the nest object "rules" have any invalid value inside – Carrie Kaski Sep 28 '22 at 15:45
  • 1
    X/Y problem, ask about that instead! – gunr2171 Sep 28 '22 at 15:46

1 Answers1

1

you can not deserialize it to JsonObject directly since your json is a JsonArray, but you can deserialize it using this code

JsonObject jObj= (JsonObject) System.Text.Json.JsonSerializer
               .Deserialize<System.Text.Json.Nodes.JsonArray>(jsonStringValue)[0];

The problem is that the "rules" property inside of your json is serialized twice. So you can parse it twice

var jsonNode = JsonNode.Parse(jsonStringValue);
jsonNode[0]["rules"] = JsonNode.Parse(jsonNode[0]["rules"]);

new json

string json= jsonNode.ToString();

result

[
  {
    "id": "001",
    "schoolName": "Johnson Primary School",
    "rules": [
      {
        "key": "bc92f",
        "student": "peter",
        "class": "6A"
      },
      {
        "key": "c929",
        "student": null,
        "class": null
      }
    ]
  }
]

or if you want a JsonObject

JsonObject jObj = (JsonObject) System.Text.Json.JsonSerializer
          .Deserialize<System.Text.Json.Nodes.JsonArray>(jsonNode.ToString())[0];
Serge
  • 40,935
  • 4
  • 18
  • 45