繁体   English   中英

如何序列化/反序列化对象

[英]How to serialize/deserialize Object

我正在编写一个Wp8 / C#库来查询MongoLab的REST Api。 我有一个像这样的abtract对象:

[DataContract]
public abstract class Entity
{
    [DataMember(Name = "_id")]
    public string _id { get; set; }
}

字段_id由Mongo自动生成为ObjectId。 但是使用WP8,我没有mongoDb C#驱动程序...序列化和反序列化不起作用....

这是我尝试过的:

var str = url;
var response = await _httpClient.GetAsync(str);
var rep = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<T>(rep);

我也尝试过Datacontractjsonserializer。

我怎样才能做到这一点?

谢谢

这是我为处理.NET 3.5中的JSON序列化和反序列化而编写的类。不要忘记添加对System.ServiceModel.Web.dll的引用

您可以使用JsonTools.ObjectToJsonString(rep);

using System;
using System.Text;
using System.Runtime.Serialization.Json;
using System.IO;

namespace Utilities
{
    /// <summary>
    /// Group of static methods for dealing with JSON.
    /// </summary>
    public static class JsonTools
    {
        /// <summary>
        /// Serializes an object to JSON string.
        /// </summary>
        /// <param name="obj">The object to serialize. </param>
        /// <returns></returns>
        /// <exception cref="System.Runtime.Serialization.InvalidDataContractException"></exception>
        /// <exception cref="System.Runtime.Serialization.SerializationException"></exception>
        /// <exception cref="System.ServiceModel.QuotaExceededExceptionn"></exception>        
        public static string ObjectToJsonString(object obj)
        {
            try
            {
                MemoryStream jsonStream = new MemoryStream();
                DataContractJsonSerializer js = new DataContractJsonSerializer(obj.GetType());
                js.WriteObject(jsonStream, obj);
                jsonStream.Position = 0;

                StreamReader sr = new StreamReader(jsonStream);
                return sr.ReadToEnd();
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// Serializes an object to JSON byte array.
        /// </summary>
        /// <param name="obj">The object to serialize. </param>
        /// <returns></returns>
        /// <exception cref="System.Runtime.Serialization.InvalidDataContractException"></exception>
        /// <exception cref="System.Runtime.Serialization.SerializationException"></exception>
        /// <exception cref="System.ServiceModel.QuotaExceededExceptionn"></exception>  
        public static byte[] ObjectToJsonByteArray(object obj)
        {
            try
            {
                MemoryStream jsonStream = new MemoryStream();
                DataContractJsonSerializer js = new DataContractJsonSerializer(obj.GetType());
                js.WriteObject(jsonStream, obj);
                jsonStream.Position = 0;

                return jsonStream.ToArray();
            }
            catch (Exception)
            {
                throw;
            }
        }


        /// <summary>
        /// Deserializes a JSON formatted string to an object of the defined type
        /// </summary>
        /// <param name="jsonString">JSON formatted string</param>
        /// <param name="objType">The type of the object which the jsonString is to be Deserialized to.</param>
        /// <returns>Deserialized object</returns>
        /// <exception cref="System.Runtime.Serialization.SerializationException"></exception>
        public static object JsonStringToObject(string jsonString, Type objType)
        {
            try
            {
                DataContractJsonSerializer js = new DataContractJsonSerializer(objType);
                byte[] jsonBytes = Encoding.Default.GetBytes(jsonString);
                MemoryStream jsonStream = new MemoryStream(jsonBytes);

                return js.ReadObject(jsonStream);
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// Deserializes a JSON formatted byte array to an object of the defined type
        /// </summary>
        /// <param name="jsonBytes">JSON formatted byte array</param>
        /// <param name="objType">The type of the object which the jsonString is to be Deserialized to.</param>
        /// <returns>Deserialized object</returns>
        /// <exception cref="System.Runtime.Serialization.SerializationException"></exception>
        public static object JsonByteArrayToObject(byte[] jsonBytes, Type objType)
        {
            try
            {
                DataContractJsonSerializer js = new DataContractJsonSerializer(objType);
                MemoryStream jsonStream = new MemoryStream(jsonBytes);

                return js.ReadObject(jsonStream);
            }
            catch (Exception)
            {
                throw;
            }
        }


    }
}

protobuf 和列表<object> - 如何序列化/反序列化?<div id="text_translate"><p> 我有一个List&lt;object&gt; ,其中包含不同类型的对象,例如整数、字符串和自定义类型。 所有自定义类型都经过 protobuf 调整。 我现在想做的是用 protobuf.net 序列化/反序列化这个列表。 到目前为止,我怀疑我必须显式声明每种类型,不幸的是,这些混合列表构造不可能做到这一点。 因为二进制格式化程序在做这些事情时没有问题,我希望我错过了一些东西,你可以帮助我。 所以我的问题是如何处理 protobuf.net 中的对象。</p></div></object>

[英]protobuf and List<object> - how to serialize / deserialize?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM