4

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
  • 823
  • 10
  • 26
user3748973
  • 449
  • 2
  • 8
  • 24

3 Answers3

11

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
  • 47,092
  • 13
  • 101
  • 128
  • 3
    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
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);
}
Nat
  • 630
  • 1
  • 5
  • 17
0

Be careful when looking at json strings as you are debugging. In Visual Studio it needs to format the value into a string. To do that it will add " so that it can process it when actually the value does not contain them. That is why the replace does not work.

Jeff Blumenthal
  • 442
  • 6
  • 8