在C#中反序列化JSON数组

本文关键字:JSON 数组 反序列化 | 更新日期: 2023-09-27 18:16:10

我有一个如下格式的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:''Work''Data.json"))
{
   string json = r.ReadToEnd();
   result = JsonConvert.DeserializeObject<List<PersonList>>(json);
}

它运行良好。

在C#中反序列化JSON数组

这应该有效。。。

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;
}

这段代码对我来说很好,

var a = serializer.Deserialize<List<Entity>>(json);
[JsonProperty("name")]
public string name { get; set; }
[JsonProperty("Age")]
public int required { get; set; }
[JsonProperty("Location")]
public string type { get; set; }

并删除一个"{"..,

strFieldString = strFieldString.Remove(0, strFieldString.IndexOf('{'));

反序列化对象。。,

   optionsItem objActualField = JsonConvert.DeserializeObject<optionsItem(strFieldString);