首页 > 解决方案 > 将类序列化为其属性之一

问题描述

当我JsonConvert使用以下代码序列化对象时:

JsonConvert.SerializeObject(new Foo())

结果是:

{"count":{"Value":3},"name":{"Value":"Tom"}}

我希望结果看起来像这样。所以没有嵌入式{ "Value": * }结构。

{"count":3,"name":Tom}

我需要使用 JObject.FromObject 和 JsonConvert.SerializeObject。


Foo 类的代码:



public class Foo
{
    public DeltaProperty<int> count = new DeltaProperty<int>(3);
    public DeltaProperty<string> name = new DeltaProperty<string>("Tom");
}

public class DeltaProperty<T>
{
    public T Value
    {
        get
        {
            m_isDirty = false;
            return m_value;
        }
        set
        {
            if (!m_value.Equals(value))
            {
                m_isDirty = true;
                m_value = value;
            }
        }
    }

    private bool m_isDirty = default;
    private T m_value = default;

    public DeltaProperty(T val)
    {
        Value = val;
    }

    public bool ShouldSerializeValue()
    {
        return m_isDirty;
    }

    public override string ToString()
    {
        return m_value.ToString();
    }
}

标签: c#jsonserializationjson.net

解决方案


推荐阅读