本文介绍了自定义NewtonSoft.Json以进行值对象序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时候,也许在DDD情况下,您可能希望使用C#创建值对象来表示数据,从而给域赋予比使用原始类型更多的含义,并且具有不变性的额外好处.

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.

例如:

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
}

布拉沃.干得好.

唯一的是,当序列化为Json时,您会得到:

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"
  }
}

极端的话,您会发现这里有很多杂音.我想做的是告诉Newtonsoft.Json,当它看到PostalCode类型时,可以将其序列化为字符串值(反之亦然).这将导致以下json:

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"
}

这可以实现吗?我看了看文档,怀疑自定义JsonConverter可能是前进的方向吗?

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

推荐答案

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

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

我认为这是您的答案?

这篇关于自定义NewtonSoft.Json以进行值对象序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 10:36