反序列化在C#中的JSON数组 [英] Deserialize a JSON array in C#

查看:138
本文介绍了反序列化在C#中的JSON数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我坚持一个棘手的问题。

I'm stuck with a tricky problem.

我有这种格式的JSON字符串:

I've a JSON string of this format:

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

在字段记录可以增加或减少。

Fields in "record" can increase or decrease.

所以,我做了类是这样的:

So, I've made classes like this:

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

public class PersonList
{
    public Person record;
}

和尝试反序列化是这样的:

And trying to deserialize like this:

JavaScriptSerializer ser = new JavaScriptSerializer();

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



我做错了什么。但无法找到。 。你能帮帮

I'm doing something wrong. But unable to find. Can you please help.

在此先感谢

更新:

其实我得到错误无效的JSON原始。由于我是越来越字符串阅读与此代码的文件:

Actually I was getting error "Invalid JSON Primitive: ." due to I was getting the string reading a file with this code:

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

现在我在看文件,这样的:

Now I'm reading the file with this:

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



它的正常工作。

It's working fine.

推荐答案

这应该工作...

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

这篇关于反序列化在C#中的JSON数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆