Newtonsoft.Json序列化/反序列化

时间:2012-06-20 09:07:28

标签: c# json

我有一些类的结构

public class PriceCampaignModel : CampaignModel, IQueryable<PriceCampaignItemModel>
{ 
    // Implementation goes here....
}

当我尝试序列化PriceCampaignModel对象时Json序列化我的oblect,如:

"$type":"Site.Infrastuctures.ModelHelpers.Campaign.PriceByProductCampaignItemModel[]...

当然,当我尝试desearealize这个对象时,我得到异常PriceCampaignItemModel[] is not campatible with PriceCampaignModel.如何使它正确序列化和反序列化?

不容易,但我试试......

public abstract class CampaignBase
{
 public CampaignModel Model { get; set; }
}

public class PriceCampaign : CampaignBase
{
...
}

public class PriceCampaignModel : CampaignModel, IQueryable<PriceCampaignItemModel>
{
...
}

public class PriceByProductCampaignItemModel 
{
 public Guid Id { get; set; }
 public string Name { get; set; }
 public Decimal Price { get; set; }
 public Decimal CampaignPrice { get; set; }
}

所以......我必须将包含PriceCampaignModel的PriceCampaign序列化为Model对象。 列出此广告系列的下一个代码

public class JsonUserType<T> : IUserType
{
    private static readonly JsonSerializerSettings _jsonSerializerSettings = 
                new JsonSerializerSettings
                {
                    TypeNameHandling = TypeNameHandling.Auto, CheckAdditionalContent = true
                };

    #region IUserType Members

    public object Assemble(object cached, object owner)
    {
        return cached;
    }

    public object DeepCopy(object value)
    {
        return value;
    }

    public object Disassemble(object value)
    {
        return value;
    }

    bool IUserType.Equals(object x, object y)
    {
        return false; //TODO: Handle with deep copying?
    }

    public int GetHashCode(object x)
    {
        return x.GetHashCode();
    }

    public bool IsMutable
    {
        get { return true; }
    }

    public object NullSafeGet(IDataReader rs, string[] names, object owner)
    {
        if (names == null) throw new ArgumentNullException("names");
        if (names.Length != 1) throw new ArgumentException(@"You can only map to one column.", "names");

        var value = rs[names[0]] as string;
        if (value != null)
        {
            return JsonConvert.DeserializeObject<T>(value, _jsonSerializerSettings);
        }
        return null;
    }

    public void NullSafeSet(IDbCommand cmd, object value, int index)
    {
        var parameter = (IDataParameter) cmd.Parameters[index];

        string json = JsonConvert.SerializeObject(value, Formatting.None, _jsonSerializerSettings);
        parameter.Value = json;
    }

    public object Replace(object original, object target, object owner)
    {
        return original;
    }

    public Type ReturnedType
    {
        get { return typeof (T); }
    }

    public SqlType[] SqlTypes
    {
        get { return new SqlType[] { new StringClobSqlType() }; }
    }

    #endregion
}

0 个答案:

没有答案