[英]Deserialize list of objects in C#
I Use JsonConvert to serialize an object and save it in a database.我使用JsonConvert序列化一个 object 并将其保存在数据库中。
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.因此,我无法Deserialize
它。
.Replace("\\","")
method doesn't create any affect on this. .Replace("\\","")
方法对此没有任何影响。 I don't know why.我不知道为什么。
You have to use JsonConvert.Deserialize
method.您必须使用JsonConvert.Deserialize
方法。
Your json
string is wrapped within square brackets ([])
, hence it is interpreted as array.您的json
字符串包含在方括号([])
,因此它被解释为数组。 Therefore, you need to deserialize
it to type
collection of one class
, for example let's call it MyClass
.因此,您需要将其deserialize
一个class
type
集合,例如我们称其为MyClass
。
public class MyClass
{
public int matId { get; set; }
public int value { get; set; }
}
Here is Deserialize
method.这是Deserialize
方法。
var results=JsonConvert.DeserializeObject<List<MyClass>>(json);
Backslashes represent serialized object.反斜杠代表序列化对象。 You need to deserialize your List object.您需要反序列化您的 List 对象。 You can try using Generics:您可以尝试使用泛型:
public List<T> Deserialize<T>(string path)
{
return JsonConvert.DeserializeObject<List<T>>(path);
}
MyClass result = JsonConvert.DeserializeObject<MyClass>(jsonString);
Be careful when looking at json strings as you are debugging.在调试时查看 json 字符串时要小心。 In Visual Studio it needs to format the value into a string.在 Visual Studio 中,它需要将值格式化为字符串。 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.为此,它会添加 " 以便在实际值不包含它们时处理它。这就是替换不起作用的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.