如果我尝试使用从List或Dictionary派生的根类反序列化一系列类,则会出现以下异常:


  “价值
  \“ System.Collections.Generic.Dictionary`2 [System.String,System.Object] \”
  的类型不是\“ JSONTesting.UserInformation \”,并且不能用于
  此通用集合。\ r \ n参数名称:值”


这是我用来创建JSON文件和反序列化的代码。这只是一个演示问题的小样本项目:

    private void BuildUserInfo(object sender, EventArgs e)
    {
      Users users = new Users();
      UserInformation userInformation;

      //Item 1
      userInformation = new UserInformation();
      userInformation.Name = "John Doe";
      userInformation.Age = "50";
      userInformation.Addresses.Add(new Address("11234 Smith Pl.", "Orlando", "FL", "32789"));
      userInformation.Addresses.Add(new Address("553 Park St.", "Boston", "MA", "02115"));
      userInformation.PhoneNumbers.Add(new PhoneNumber("617", "111-2222", string.Empty));
      userInformation.PhoneNumbers.Add(new PhoneNumber("508", "236-0173", "22734"));
      users.Add(userInformation);

      //Serialize
      JavaScriptSerializer serializer = new JavaScriptSerializer();
      StreamWriter streamOut = null;
      string outString = string.Empty;

      outString = serializer.Serialize(users);
      streamOut = new StreamWriter("OUTFILE.JSON");
      streamOut.Write(outString);

      streamOut.Close();
    }

    private void ReadUserInfo(object sender, EventArgs e)
    {
      JavaScriptSerializer serializer;
      StreamReader streamIn = null;
      Users retrievedUsers = null;

      if (File.Exists("OUTFILE.JSON"))
      {
        streamIn = new StreamReader("OUTFILE.JSON");
        serializer = new JavaScriptSerializer();
        retrievedUsers = serializer.Deserialize<Users>(streamIn.ReadToEnd());

        streamIn.Close();
      }
    }
  }

  public class Users: List<UserInformation>
  {
    public UserInformation getUserByName(string name)
    {
      foreach (UserInformation user in this)
      {
        if (name == user.Name)
          return user;
      }

      return null;
    }
  }

  public class UserInformation
  {
    public string Name;
    public string Age;

    public List<Address> Addresses;
    public List<PhoneNumber> PhoneNumbers;

    public UserInformation()
    {
      Name = string.Empty;
      Age = string.Empty;
      Addresses = new List<Address>();
      PhoneNumbers = new List<PhoneNumber>();
    }

    public UserInformation(string Name, string Age)
    {
      this.Name = Name;
      this.Age = Age;
      Addresses = new List<Address>();
      PhoneNumbers = new List<PhoneNumber>();
    }
  }

  public class Address
  {
    public string Street;
    public string City;
    public string State;
    public string PostalCode;

    public Address()
    {
      Street = string.Empty;
      City = string.Empty;
      State = string.Empty;
      PostalCode = string.Empty;
    }

    public Address(string Street, string City, string State, string PostalCode)
    {
      this.Street = Street;
      this.City = City;
      this.State = State;
      this.PostalCode = PostalCode;
    }
  }

  public class PhoneNumber
  {
    public string AreaCode;
    public string Number;
    public string Extension;

    public PhoneNumber()
    {
      AreaCode = string.Empty;
      Number = string.Empty;
      Extension = string.Empty;
    }

    public PhoneNumber(string AreaCode, string Number, string Extension)
    {
      this.AreaCode = AreaCode;
      this.Number = Number;
      this.Extension = Extension;
    }
  }


这是BuildUserInfo函数生成的JSON:

    [
      {
        "Name": "John Doe",
        "Age": "50",
        "Addresses": [
          {
            "Street": "11234 Smith Pl.",
            "City": "Orlando",
            "State": "FL",
            "PostalCode": "32789"
          },
          {
            "Street": "553 Park St.",
            "City": "Boston",
            "State": "MA",
            "PostalCode": "02115"
          }
        ],
        "PhoneNumbers": [
          {
            "AreaCode": "617",
            "Number": "111-2222",
            "Extension": ""
          },
          {
            "AreaCode": "508",
            "Number": "236-0173",
            "Extension": "22734"
          }
        ]
      }
    ]


如果我更改Users类,以便它不是从List派生的,而只是使其成为具有内部List集合的类,则它可以正常工作。一个例子:

public class Users
{
  public List<UserInformation> UserItems = new List<UserInformation>();
}


为了能够反序列化此JSON,我需要更改什么?

编辑:尝试从下面的评论链接,我更改为以下内容:

public class Users(IEnumerable<UserInformation> collection) : base (collection) {

}


我收到构建错误:


  错误1在类,结构或接口成员中的无效令牌'('
  声明c:\ Local .NET
  Projects \ 2010 \ JSONTesting1 \ Form1.cs 66 25 JSONTesting1错误2 {
  预期的c:\ Local .NET
  Projects \ 2010 \ JSONTesting1 \ Form1.cs 66 25 JSONTesting1错误3;
  预期的c:\ Local .NET
  Projects \ 2010 \ JSONTesting1 \ Form1.cs 66 69 JSONTesting1错误4无效
  类,结构或接口成员声明c:\ Local中的标记')'
  .NET Projects \ 2010 \ JSONTesting1 \ Form1.cs 66 93 JSONTesting1错误5}
  预期的c:\ Local .NET
  Projects \ 2010 \ JSONTesting1 \ Form1.cs 153 2 JSONTesting1

最佳答案

您必须使用JavaScriptSerializer吗?如果这样做,那么我们必须缺少一些配置详细信息,但是Newtonsoft.Json无需任何调整即可处理这种情况:

private static void BuildUserInfo()
{
    // ...

    //Serialize
    File.WriteAllText("OUTFILE.JSON", Newtonsoft.Json.JsonConvert.SerializeObject(users));
}

private static void ReadUserInfo()
{
    Users retrievedUsers = null;

    if (File.Exists("OUTFILE.JSON"))
    {
        var json = File.ReadAllText("OUTFILE.JSON");

        retrievedUsers = Newtonsoft.Json.JsonConvert.DeserializeObject<Users>(json);
    }
}

关于c# - C#JSON反序列化异常,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54889542/

10-09 04:42