如何序列化/反序列化ArrayList和对象类型的属性

时间:2019-12-08 22:25:11

标签: c# json json.net

反序列化json对象时,如何获得相同的对象类型? ArrayList丢失并反序列化为对象数组,矩形完全丢失。

编辑:我不能更改对象类型,有效载荷必须是对象类型,我不知道其中的内容。我仅添加了其中包含的一个数据示例,但是会有所不同。

  public static void Run()
  {
     Int32 retval = 0;
     ArrayList list = new ArrayList();

     list.Add(retval);
     list.Add(new Rectangle(1, 1, 1, 1));

     Bar bar = new Bar()
     {
        MessageType = Bar.MessageTypes.Msg1,
        Payload = list
     };
     Newtonsoft.Json.JsonSerializerSettings settings = new Newtonsoft.Json.JsonSerializerSettings()
     {
        TypeNameHandling = Newtonsoft.Json.TypeNameHandling.Auto
     };

     var json1 = Newtonsoft.Json.JsonConvert.SerializeObject(bar);
     var temp1 = Newtonsoft.Json.JsonConvert.DeserializeObject<Bar>(json1);

     var json2 = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(bar);
     var temp2 = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<Bar>(json2);

  }

  public class Bar
  {
     public enum MessageTypes
     {
        Msg1 = 1,
        Msg2 = 2
     }

     public MessageTypes MessageType { get; set; }
     public Object Payload { get; set; }
  }

2 个答案:

答案 0 :(得分:0)

它无法反序列化,因为它不知道需要序列化为的类型。 不要使用ArrayList,请尝试指定有效负载的属性。这样的事情应该起作用:

public enum MessageTypes
{
    Msg1 = 1,
    Msg2 = 2
}

public class PayLoad
{
    public int Foo { get; set; }
    public Rectangle Rectangle { get; set; }
}

public class Bar
{
    public MessageTypes MessageType { get; set; }
    public PayLoad Payload { get; set; }
}

答案 1 :(得分:0)

我决定改用肥皂序列化,因为它将类型添加到xml

  using System;
  using System.Text;
  using System.IO;
  using System.Runtime.Serialization.Formatters;
  using System.Runtime.Serialization.Formatters.Soap;

  namespace Utils
  {
     public class XMLUtil
     {
        public static Byte[] StringToUTF8ByteArray(String xmlString)
        {
           return new UTF8Encoding().GetBytes(xmlString);
        }

        public static String SerializeToXML<T>(T objectToSerialize)
        {
           using (MemoryStream ms = new MemoryStream())
           using (StreamWriter sw = new StreamWriter(ms, Encoding.UTF8))
           {
              SoapFormatter soapFormatter = new SoapFormatter();
              soapFormatter.AssemblyFormat = FormatterAssemblyStyle.Simple;
              soapFormatter.Serialize(ms, objectToSerialize);
              String decoded = Encoding.UTF8.GetString(ms.ToArray());
              return decoded;
           }
        }

        public static T DeserializeFromXML<T>(string xmlString) where T : class
        {
           T retval = default(T);
           using (MemoryStream stream = new MemoryStream(StringToUTF8ByteArray(xmlString)))
           {
              SoapFormatter soapFormatter = new SoapFormatter();
              soapFormatter.AssemblyFormat = FormatterAssemblyStyle.Simple;
              retval = soapFormatter.Deserialize(stream) as T;
           }
           return retval;
        }
     }
  }