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.

+3


source to share


2 answers


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);

      

+5


source


The backslash represents a serialized object. You need to deserialize the List object. You can try using Generics:



public List<T> Deserialize<T>(string path)
{
   return JsonConvert.DeserializeObject<List<T>>(path);
}

      

+1


source







All Articles