Dot-Net

JSON.NET 序列化問題

  • August 22, 2019

我有一個屬性類型為 Point 的類( .NET Framework 中的 struct )。我使用 Newton.Json 中的 JsonConvert 將其序列化為 JSON。但結果是

"Point" : "100,100" 

代替

"Point" : { X: "100", Y: "100"}

當我用標準的 JavascriptSerializer 替換 JsonConvert 時,一切正常。

但我想使用 JSON.Net 中的 JsonConverter,因為它要快得多。

那是因為Point已經定義了自己的TypeConverter並且 JSON.NET 使用它來進行序列化。我不確定是否有一種干淨的方法可以關閉此行為,但您當然可以創建自己的JsonConverter行為方式:

class PointConverter : JsonConverter
{
   public override void WriteJson(
       JsonWriter writer, object value, JsonSerializer serializer)
   {
       var point = (Point)value;

       serializer.Serialize(
           writer, new JObject { { "X", point.X }, { "Y", point.Y } });
   }

   public override object ReadJson(
       JsonReader reader, Type objectType, object existingValue,
       JsonSerializer serializer)
   {
       var jObject = serializer.Deserialize<JObject>(reader);

       return new Point((int)jObject["X"], (int)jObject["Y"]);
   }

   public override bool CanConvert(Type objectType)
   {
       return objectType == typeof(Point);
   }
}

然後你可以像這樣使用它:

JsonConvert.SerializeObject(
   new { Point = new Point(15, 12) },
   new PointConverter())

引用自:https://stackoverflow.com/questions/9750836