6

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.

LopDev
  • 815
  • 8
  • 25
user3748973
  • 643
  • 2
  • 7
  • 20

2 Answers2

10

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);
Mihai Alexandru-Ionut
  • 44,345
  • 11
  • 88
  • 115
  • 1
    I get an error when I Deserialize , `Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'my type' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.` – user3748973 Apr 14 '17 at 17:19
1

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);
}
Nat
  • 510
  • 4
  • 14