【问题标题】:Deserialize a JSON array in C#在 C# 中反序列化 JSON 数组
【发布时间】:2013-05-27 05:58:42
【问题描述】:

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

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

一切正常。

【问题讨论】:

  • .net 应该如何知道您想要一个名为 "record" 的 javascript 对象的 Person 对象?
  • 如果可以的话,我强烈推荐使用JSON.NET。然后你可以打电话给JsonConvert.DeserializeObject&lt;List&lt;Person&gt;&gt;(jsonData)
  • 错误是:无效的 JSON 原语:.
  • 我遇到了类似的问题,直到上面的@valverij 评论解决了我的问题。 >

标签: c# json deserialization json-deserialization


【解决方案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;
}

【讨论】:

    【解决方案2】:

    这段代码对我来说很好用,

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

    【讨论】:

      【解决方案3】:
      [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);
      

      【讨论】:

        猜你喜欢
        • 2017-01-18
        • 2013-02-13
        • 2021-05-04
        • 1970-01-01
        • 2021-10-13
        • 2017-10-16
        • 2012-09-20
        • 2011-10-19
        • 1970-01-01
        相关资源
        最近更新 更多