JSON字典错误



我读取了json文件并设置了一个字符串变量,我使用的是System.Web.Script.Serialization;

FileStream fs = new FileStream(Server.MapPath("odul_en.json"),FileMode.Open,FileAccess.Read);
StreamReader sr = new StreamReader(fs);
string jsonGelen = sr.ReadToEnd();
var serializer = new JavaScriptSerializer();
var dict = serializer.Deserialize<Dictionary<string, object>>(jsonGelen);

当我放置断点"vardict=serializer.Deserialize>(jsonGelen(;"行时,我得到以下错误;

System.Collections.Generic.Dictionary `2[[System.String,mscorlib,Version=2.0.0.0,Culture=neutral,PublicKeyToken=b77a5c561934e089],[System.Object,mscorllib,Version=22.0.0.0,Culture=neutral

modul_en.json如下;

[{
"odulID": "130",
"Ad": "LaQ Creative Toy / Basic 001",
"Aciklama": "Instead of the gift product, the product is not paid for the price, can not be turned into money. There is no guarantee of the products because of collective purchase. Buying gift product is not returned. Photos are representative, products may vary."},{
"odulID": "132",
"Ad": "Selfie Stick",
"Aciklama": "Instead of the gift product, the product is not paid for the price, can not be turned into money. There is no guarantee of the products because of collective purchase. Photos are representative, products may vary. Buying gift product is not returned. There is no color option. Suitable for Phones, easy to carry. The open length is 100 cm and the closed length is 23 cm"}]

我寻找解决方法;有人在json文件中说"去掉方括号",但没有解决。(我的.net框架3.5,不能使用动态(我该怎么解决这个问题,谢谢。

实际上,仔细观察JSON,我看不出它是如何工作的。您希望在字典中每个条目的"字符串"键中放入什么?由于JSON是一个数组,因此它没有为每个条目指定一个命名键。如果您尝试使用JSON.NET对其进行反序列化,则异常消息会通知您,取消对这种字典结构的序列化需要JSON是一个对象(带有命名键(,而不是数组。

您最好取消序列化为一个自定义类型的列表,该列表包含与JSON中的字段匹配的属性。这里有一个例子,再次使用JSON.NET(也称为Newtonsoft.JSON(:

型号类别:

public class Product
{
public int odulID { get; set; }
public string Ad { get; set; }
public string Aciklama { get; set; }
}

沙漠化代码:

FileStream fs = new FileStream(Server.MapPath("odul_en.json"),FileMode.Open,FileAccess.Read);           
StreamReader sr = new StreamReader(fs);
string jsonGelen = sr.ReadToEnd();
var list = JsonConvert.DeserializeObject<List<Product>>(jsonGelen);

modul_en.json是json数组,修复如下:

FileStream fs = new FileStream(Server.MapPath("odul_en.json"), FileMode.Open, FileAccess.Read);
StreamReader sr = new StreamReader(fs);
string jsonGelen = sr.ReadToEnd();
var serializer = new JavaScriptSerializer();
var dict = serializer.Deserialize<List<Dictionary<string, object>>>(jsonGelen);

最新更新