反序列化C#中的对象列表 [英] Deserialize list of objects in C#
问题描述
我使用 JsonConvert 序列化对象并将其保存在数据库中.这是我保存在数据库中的序列化字符串的示例:
I Use JsonConvert to serialize object and save it on database. It's sample of serialize string that I save in database:
[{"matId":"1","value":"44"},{"matId":"2","value":"55"},{"matId":"4","value":"77"}]
现在,当我从db获取此字符串时,它会有很多反斜杠,如下所示:
Now when I get this string from db it has a lot of backslash like this:
"[{\"matId\":\"1\",\"value\":\"44\"},{\"matId\":\"2\",\"value\":\"55\"},{\"matId\":\"4\",\"value\":\"77\"}]"
由于这个原因,我不能Deserialize
它.
And for this reason I can't Deserialize
it.
.Replace("\\","")
方法对此没有任何影响.我不知道为什么.
.Replace("\\","")
method doesn't any affect on this. I don't know why.
推荐答案
您必须使用JsonConvert.Deserialize
方法.
您的json
字符串被包装在方括号([])
中,因此将其解释为数组.因此,您需要将其deserialize
转换为一个class
的type
集合,例如,将其称为MyClass
.
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; }
}
这是Deserialize
方法.
var results=JsonConvert.DeserializeObject<List<MyClass>>(json);
这篇关于反序列化C#中的对象列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!