加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

在C#中反序列化一个JSON数组

发布时间:2020-12-15 07:38:57 所属栏目:百科 来源:网络整理
导读:我遇到棘手的问题. 我有一个这样格式的JSON字符串: [{ "record": { "Name": "Komal","Age": 24,"Location": "Siliguri" } },{ "record": { "Name": "Koena","Age": 27,"Location": "Barasat" } },{ "record": { "Name": "Kanan","Age": 35,"Location": "Utt
我遇到棘手的问题.

我有一个这样格式的JSON字符串:

[{
  "record":
          {
             "Name": "Komal","Age": 24,"Location": "Siliguri"
          }
 },{
  "record":
          {
             "Name": "Koena","Age": 27,"Location": "Barasat"
          }
 },{
  "record":
          {
             "Name": "Kanan","Age": 35,"Location": "Uttarpara"
          }
 }
... ...
]

“记录”中的字段可以增加或减少.

所以,我做了这样的课程:

public class Person
{
    public string Name;
    public string Age;
}

public class PersonList
{
    public Person record;
}

并试图反序列化这样:

JavaScriptSerializer ser = new JavaScriptSerializer();

var r = ser.Deserialize<PersonList>(jsonData);

我在做错事但无法找到.你能帮忙吗

提前致谢.

更新:

其实我得到错误“无效的JSON原始:”.由于我正在使用该代码读取文件的字符串:

public static bool ReadFromFile(string path,string fileName,out string readContent)
{
   bool status = true;

   byte[] readBuffer = null;
   try
   {
      // Combine the new file name with the path
      string filePath = System.IO.Path.Combine(path,fileName);
      readBuffer = System.IO.File.ReadAllBytes(filePath);
   }
   catch (Exception ex)
   {
       status = false;
   }

   readContent = (null != readBuffer) ? Utilities.GetString(readBuffer) : string.Empty;

   return status;
}

现在我正在读这个文件:

using (StreamReader r = new StreamReader("E:WorkData.json"))
{
   string json = r.ReadToEnd();
   result = JsonConvert.DeserializeObject<List<PersonList>>(json);
}

工作正常

解决方法

这应该工作…
var records = new ser.Deserialize<List<Record>>(jsonData);

public class Person
{
    public string Name;
    public int Age;
    public string Location;
}
public class Record
{
    public Person record;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读