Deserialize list of objects in c #
I am using JsonConvert to serialize an object and store it in a database. This is a sample serialization of a string that I am storing in the database:
[{"matId":"1","value":"44"},{"matId":"2","value":"55"},{"matId":"4","value":"77"}]
Now when I get this line from db it has a big backslash like this:
"[{\"matId\":\"1\",\"value\":\"44\"},{\"matId\":\"2\",\"value\":\"55\"},{\"matId\":\"4\",\"value\":\"77\"}]"
And for this reason, I cannot have Deserialize
it.
.Replace("\\","")
the method does not affect this. I do not know why.
source to share
You must use the method JsonConvert.Deserialize
.
Your string is json
enclosed in square brackets ([])
, so it is interpreted as an array. So you need deserialize
it in the type
collection of one class
, for example, call it MyClass
.
public class MyClass
{
public int matId { get; set; }
public int value { get; set; }
}
Below is the method deserialize
.
var results=JsonConvert.DeserializeObject<List<MyClass>>(json);
source to share