I have a class Product with following properties:
public class Product
{
public string id { get; set; }
public JsonObject details { get; set; }
}
An example of data in details field sent using POST request is:
{
"id": "1",
"type": "icecream",
"name": "Vanilla Cone",
"image":
{
"url": "img/01.png",
"width": 200,
"height": 200
}
}
I am writing unit test for this class and methods. So earlier I put this structure in a string like :
details = "\{ \"id\":\"1\", \"type\": \"icecream\"\}, "
So now it is giving me an error that it cannot convert string type to jsonObject. Is there a way to convert such string into JsonObject?
CodePudding user response:
string json = @"{
"id": "1",
"type": "icecream",
"name": "Vanilla Cone",
"image":
{
"url": "img/01.png",
"width": 200,
"height": 200
}
}";
JObject o = JObject.Parse(json);
CodePudding user response:
you can use this code to convert a json string to your class
JsonObject jsonObj=System.Text.Json.JsonSerializer.Deserialize<JsonObject>(json);
Product product = new Product {id=(string) jsonObj["id"], details=jsonObj};
jsonObj.Remove("id");