Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 776
user3748973 Avatar asked Apr 14 '17 17:04

user3748973


People also ask

What is deserialization in C?

Serialization is the process of converting an object into a stream of bytes to store the object or transmit it to memory, a database, or a file. Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called deserialization.

What is deserialize object?

Deserialization is the process of reconstructing a data structure or object from a series of bytes or a string in order to instantiate the object for consumption. This is the reverse process of serialization, i.e., converting a data structure or object into a series of bytes for storage or transmission across devices.


2 Answers

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);
like image 168
Mihai Alexandru-Ionut Avatar answered Sep 30 '22 15:09

Mihai Alexandru-Ionut


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);
}
like image 26
Nat Avatar answered Sep 30 '22 16:09

Nat