Deserialize list of objects in C#

I Use JsonConvert to serialize an object and save it in a database.
This is a sample of the serialized string that I saved in database:

[{"matId":"1","value":"44"},{"matId":"2","value":"55"},{"matId":"4","value":"77"}]

Now when I get this string from database which has a lot of backslashes like this:

"[{"matId":"1","value":"44"},{"matId":"2","value":"55"},{"matId":"4","value":"77"}]"

And for this reason I can’t Deserialize it.

.Replace("\","") method doesn’t create any affect on this. I don’t know why.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You have to use JsonConvert.Deserialize method.

Your json string is wrapped within square brackets ([]), hence it is interpreted as array. Therefore, you need to deserialize it to type collection of one class, for example let’s call it MyClass.

public class MyClass
{
    public int matId { get; set; }
    public int value { get; set; }
}

Here is Deserialize method.

var results=JsonConvert.DeserializeObject<List<MyClass>>(json);

Method 2

Backslashes represent serialized object.
You need to deserialize your List object.
You can try using Generics:

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x