1

Json.net4.5を使用しています。Jsonを使用してPatientV1をシリアル化し、PatientV2に脱滅菌してみました。シリアル化はうまく行われます。

しかし、検証チェックインAppUtility.CreatePatientNr(空またはnullの値が渡された場合に例外をスローする)を導入すると、逆シリアル化は失敗します。

派生したJsonConverterを使用してPatientV2オブジェクトを作成しようとしましたが、コンストラクターに「適切な」値を渡すためのコントロールがありますが、オブジェクトが作成された後は読み取り専用であるため、適切なPatientNrを設定できません。

リフレクションは使いたくない。Json.netは、JsonConverterで読み取り専用プロパティを設定する方法を提供していますpatientV2.PatientNrか?

この例外を無視する方法や、PatientV2オブジェクトを作成する他の方法はありますか?

    //version 1.0. Legacy code with no Json tag
    public class PatientV1
    {
        public int PatId { get; set; }
    }

    //Version 2.0
    public class PatientV2
    {
        public PatientV2( string Id, string s1, string s2 )
        {
            PatientNr = AppUtility.CreatePatientNr( Id, s1, s2);
        }

        //PatId is renamed to a string type. It now has private set
        [JsonProperty( "PatId" )]
        public string PatientNr { get; private set; }
    }

Edit1: Jsonには、バイナリシリアル化と同じように、逆シリアル化のための特定のコンストラクターがありますか?

4

1 に答える 1

0

Json first tries the object using default constructor and if it does not find one then it then takes up the first parameterized constructor and pass null data to it. There is no specific constructor that Json uses for construction of object just like binary serialization.

However if you are have object which implements ISerializable then serialization constructor is called.

Approaches one can use are as follows

  1. In the JsonConverter create object by passing appropriate value to the parameterized constructor
  2. Remove the business logic from constructor that might raise an exception.
  3. Make all the persist-able as simply a structure without any business logic (Anemic model)

I will currently will go with approach 1) then 2) later 3). Because of legacy huge code reason approaches 2) and 3) will take some time

于 2012-11-19T05:32:30.433 に答える