反序列化C#中的对象列表 [英] Deserialize list of objects in C#

查看:330
本文介绍了反序列化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转换为一个classtype集合,例如,将其称为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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆