小编典典

在C#中反序列化JSON数组

c#

我遇到了一个棘手的问题。

我有这种格式的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);

我做错了。但是找不到。你能帮忙吗?

提前致谢。

更新:

实际上,我收到错误消息“ Invalid JSON Primitive:。” 由于我正在使用此代码读取文件的字符串:

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:\\Work\\Data.json"))
{
   string json = r.ReadToEnd();
   result = JsonConvert.DeserializeObject<List<PersonList>>(json);
}

一切正常。


阅读 603

收藏
2020-05-19

共1个答案

小编典典

这应该工作…

JavaScriptSerializer ser = new JavaScriptSerializer();
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;
}
2020-05-19