反序列化json - 错误类型

时间:2014-11-03 09:21:23

标签: c# json deserialization

这是我如何尝试反序列化我的json:

new JavaScriptSerializer().Deserialize<Dictionary<int, MyModel>>(myData);

这是班级:

public class MyModel
{
    public Dictionary<int, ItemModel> Translation { get; set; }

    public int Id { get; set; }
}

public class ItemModel
{
    public string Name { get; set; }

    public string ShortDescription { get; set; }

    public string LongDescription { get; set; }
}

这里是json:

"[[],[],{"Translation":{"1":{"Name":"Bla1","ShortDescription":"bla1","LongDescription":"bla1"},"2":{"Name":"BlaUS1","ShortDescription":"BlaUS1","LongDescription":"BlaUS1"}},"Id":"12"},{"Translation":{"1":{"Name":"Bla22","ShortDescription":"bla22","LongDescription":"bla22"},"2":{"Name":"Bla2US2","ShortDescription":"Bla2US2","LongDescription":"Bla2US2"}},"Id":"13"}]"

我得到的错误是该类型不支持反序列化。

我的错误在哪里?

2 个答案:

答案 0 :(得分:1)

首先,你的JSON对我来说有点不对劲。它是4个元素和前两个元素的数组是空数组,但其他两个对象?我怀疑你的JSON应该是这样的:

  

“[{” 翻译 “:{” 1 “:{” 名称 “:” BLA1" , “SHORTDESCRIPTION”: “BLA1”, “LongDescription”: “BLA1”}, “2”:{ “名称”: “BlaUS1”, “SHORTDESCRIPTION”: “BlaUS1”, “LongDescription”: “BlaUS1”}}, “ID”: “12”},{ “翻译”:{ “1”:{ “名称”: “Bla22”, “SHORTDESCRIPTION”: “bla22”, “LongDescription”: “bla22”}, “2”:{ “名称”: “Bla2US2”, “SHORTDESCRIPTION”: “Bla2US2”, “LongDescription”: “Bla2US2”}},“ID “:” 13 “}]”

另一个问题是您有Dictionary<int, ItemModel>但是对于序列化/反序列化,您必须拥有StringObject类型的密钥。

工作示例(假设您已从Dictionary<int, ItemModel>更改为Dictionary<object, ItemModel>)

string input = "[{\"Translation\":{\"1\":{\"Name\":\"Bla1\",\"ShortDescription\":\"bla1\",\"LongDescription\":\"bla1\"},\"2\":{\"Name\":\"BlaUS1\",\"ShortDescription\":\"BlaUS1\",\"LongDescription\":\"BlaUS1\"}},\"Id\":\"12\"},{\"Translation\":{\"1\":{\"Name\":\"Bla22\",\"ShortDescription\":\"bla22\",\"LongDescription\":\"bla22\"},\"2\":{\"Name\":\"Bla2US2\",\"ShortDescription\":\"Bla2US2\",\"LongDescription\":\"Bla2US2\"}},\"Id\":\"13\"}]";

List<MyModel> myModels = new JavaScriptSerializer().Deserialize<List<MyModel>>(input);

答案 1 :(得分:0)

你的字符串表明你所拥有的是一个JSON数组,例如: - [1,2,3]

但是你试图将它反序列化为一个json表示类似于

的字典
{"1":"Hai","2":"Hello"}
显然,库正在抛出一个错误。可能是为什么你不使用以下来反序列化字符串。

new JavaScriptSerializer().Deserialize<List<MyModel>[]>(myData)

但是,要使用它,你不能在json中有空数组,你必须用属性的默认值填充它们。

要证明上述方法有效,请尝试

"[{"Translation":{"1":{"Name":"Bla1","ShortDescription":"bla1","LongDescription":"bla1"},"2":  {"Name":"BlaUS1","ShortDescription":"BlaUS1","LongDescription":"BlaUS1"}},"Id":"12"},{"Translation":{"1":{"Name":"Bla22","ShortDescription":"bla22","LongDescription":"bla22"},"2":{"Name":"Bla2US2","ShortDescription":"Bla2US2","LongDescription":"Bla2US2"}},"Id":"13"}]"

new JavaScriptSerializer().Deserialize<List<MyModel>>(myData)