【问题标题】:How to serialize/deserialize Object如何序列化/反序列化对象
【发布时间】:2014-02-28 22:03:28
【问题描述】:

我正在编写一个 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。

我该怎么做?

谢谢

【问题讨论】:

  • 你不需要在标题中放标签信息,这就是标签的作用。
  • 你试过什么 - 你说序列化等不起作用 - 你能分享不起作用的代码吗?
  • 你不能序列化/反序列化抽象类。
  • 即使我的类不是抽象类,序列化或反序列化失败

标签: c# mongodb windows-phone-8 bson mlab


【解决方案1】:

这是我为在 .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;
            }
        }


    }
}

【讨论】:

  • 它可以工作,但我的 _id 是一个 Dictionnary[string, object] 并且它不适用于此类...
  • 我不认为你可以用一个通用类型的 Object 来做到这一点
猜你喜欢
  • 2011-02-27
  • 2015-06-28
  • 2011-04-06
  • 1970-01-01
  • 1970-01-01
  • 2012-04-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多