0

When I serialize an object using JsonConvert using the following code:

JsonConvert.SerializeObject(new Foo())

The result is:

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

I would like the result to look like this. So without the embedded { "Value": * } structure.

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

I need use JObject.FromObject and JsonConvert.SerializeObject.


The code for the Foo class:



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();
    }
}
GvS
  • 52,015
  • 16
  • 101
  • 139
  • You will need to use a JsonConverter to do this. The [ToStringJsonConverter](https://stackoverflow.com/a/22355712/10263) from [How to make JSON.Net serializer to call ToString() when serializing a particular type?](https://stackoverflow.com/q/22354867/10263) might work for your case. – Brian Rogers Aug 22 '19 at 15:19
  • Serializing the return of `ToString()` is not necessarily a good idea, because the return can be localized, thus preventing exchange of JSON data between locales. For instance, a `double` or `decimal` may use a `.` or `,` as decimal separator depending on locale. Unless `T` is restricted to be `IConvertible` it's better to use a custom `JsonConverter` that serializes and deserializes the `Value` explicitly. – dbc Aug 22 '19 at 19:34
  • I notice you have a `ShouldSerialize*()` method for `Value`. If you serialize `DeltaProperty` as its value, rather than as an object, `ShouldSerializeValue()` is never going to get called. There's no built-in way for a child to tell its parent not to serialize it. Can you explain your requirement here? – dbc Aug 22 '19 at 19:36
  • @dbc A fair point. – Brian Rogers Aug 22 '19 at 21:18
  • For a general answer for how to serialize an object as a primitive value see [Json.Net: Serialize/Deserialize property as a value, not as an object](https://stackoverflow.com/q/40480489/3744182) as well as the answer linked to above. Without some explanation of your requirement for `ShouldSerializeValue()` I don't think we can give you a concrete answer. Maybe you want something like `IConditionalSerialization` and `ShouldSerializeContractResolver` from [JSON.Net custom contract serialization and Collections](https://stackoverflow.com/a/38043874/3744182)? – dbc Aug 29 '19 at 17:11

0 Answers0