Customise NewtonSoft.Json for Value Object serialisation [duplicate]

末鹿安然 提交于 2019-12-10 17:36:00

问题


Sometimes, perhaps in a DDD situation, you might want to use C# to create Value Objects to represent data, to give more meaning to your domain than using primitive types would, with the added benefit of being immutable.

For example:

public class PostalCode // Bit like a zipcode
{
    public string Value { get; private set; }

    public PostalCode(string value)
    {
        Value = value;
    }

    // Maybe sprinkle some ToString()/Equals() overrides here
}

Bravo. Well done me.

The only thing is, when serialised to Json, you get this:

{
    "Value": "W1 AJX"
}

That sort of looks okay, but when it's used as a property of an object (let's say an address) then it looks like this:

{
  "Line1": "Line1",
  "Line2": "Line2",
  "Line3": "Line3",
  "Town": "Town",
  "County": "County",
  "PostalCode": {
    "Value": "W1 AJX"
  }
}

Taken to an extreme, you can see there's a lot of noise here. What I'd like to do, is tell Newtonsoft.Json, that when it sees a type of PostalCode, that it can serialise it to a string value (and vice versa). That would result in the following json:

{
  "Line1": "Line1",
  "Line2": "Line2",
  "Line3": "Line3",
  "Town": "Town",
  "County": "County",
  "PostalCode": "W1 AJX"
}

Is this achievable? I've had a look through the docs and I suspect a custom JsonConverter might be the way forward?


回答1:


public class PostalCode // Bit like a zipcode
{
    [JsonProperty(PropertyName = "PostalCode")]
    public string Value { get; set; }

    // Maybe sprinkle some ToString()/Equals() overrides here
}

I think this is your answer?




回答2:


Could you leverage the implicit operator syntax?

https://msdn.microsoft.com/en-us/library/z5z9kes2.aspx

public class PostalCode
{
     public string Value { get; private set; }

     public PostalCode(string value)
     {
         this.Value = value;
     }

     public static implicit operator string(PostalCode result)
     {
         return result.Value;
     }
 }


var postCode = new PostalCode("WN11 2PZ");
Console.Output(postCode);  // "WN11 2PZ"

I haven't tested this so I could be way off!



来源:https://stackoverflow.com/questions/43780979/customise-newtonsoft-json-for-value-object-serialisation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!