在C#中反序列化JSON数组

mm5n2pyu  于 2022-12-24  发布在  C#
关注(0)|答案(3)|浏览(212)

我有一个如下格式的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);
}

一切正常

23c0lvtd

23c0lvtd1#

应该可以...

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

nsc4cvqm2#

这个代码对我来说很好用

var a = serializer.Deserialize<List<Entity>>(json);
4nkexdtk

4nkexdtk3#

[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);

相关问题