有没有更好的方式来处理与Json.Net编码值? [英] Is there a better way to handle Encoding values with Json.Net?

查看:202
本文介绍了有没有更好的方式来处理与Json.Net编码值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我序列化/反序列化与Json.Net类型System.Text.Encoding的属性的类。尝试了一个简单的测试,我的课系列化没有任何问题:

I am serializing/deserializing a class that has a property of type System.Text.Encoding with Json.Net. Trying out a simple test, my class serialized without any issue:

public class TestClass {
    public Encoding TheEncoding { get; set; }
}

var testClass = new TestClass { TheEncoding = Encoding.UTF8 };
var json = JsonConvert.SerializeObject( testClass, Formatting.Indented );
var obj = JsonConvert.DeserializeObject<TestClass>( json );



序列化为:

Serializes to:

{
  "TheEncoding": {
    "BodyName": "utf-8",
    "EncodingName": "Unicode (UTF-8)",
    "HeaderName": "utf-8",
    "WebName": "utf-8",
    "WindowsCodePage": 1200,
    "IsBrowserDisplay": true,
    "IsBrowserSave": true,
    "IsMailNewsDisplay": true,
    "IsMailNewsSave": true,
    "IsSingleByte": false,
    "EncoderFallback": {
      "DefaultString": "?",
      "MaxCharCount": 1
    },
    "DecoderFallback": {
      "DefaultString": "?",
      "MaxCharCount": 1
    },
    "IsReadOnly": true,
    "CodePage": 65001
  }
}

然而,反序列化的时候,我得到了一个例外:

However, when deserializing, I got an exception:

无法创建类型System.Text.Encoding的一个实例。类型是
接口或抽象类和不能被实例化。路径
'TheEncoding.BodyName',3号线,位置16。

Could not create an instance of type System.Text.Encoding. Type is an interface or abstract class and cannot be instantiated. Path 'TheEncoding.BodyName', line 3, position 16.

我能够通过创建让过去这个问题处理该System.Text.Encoding类型的定制转换器:

I was able to get past this issue by creating a custom converter that handles the System.Text.Encoding type:

public class JsonEncodingConverter : JsonConverter {
    public override void WriteJson( JsonWriter writer, object value, JsonSerializer serializer ) {
        // Serialize as the BodyName.
        serializer.Serialize( writer, ( value as Encoding ).BodyName );
    }

    public override object ReadJson( JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer ) {
        // Already good to go.
        return existingValue;
    }

    public override bool CanConvert( Type objectType ) {
        return ( typeof ( Encoding ).IsAssignableFrom( objectType ) );
    }
}

var testClass = new TestClass { TheEncoding = Encoding.UTF8 };
var json = JsonConvert.SerializeObject( testClass, Formatting.Indented, new JsonEncodingConverter() );
var obj = JsonConvert.DeserializeObject<TestClass>( json , new JsonEncodingConverter() );



在自定义转换序列化现在生产:

Serializing with the custom converter now produces:

{
  "TheEncoding": "utf-8"
}

和这个JSON可以成功往返的回用时,定制转换器反序列化原始对象。

And this JSON can be successfully round-tripped back to the original object when deserialized with the custom converter.

我是新来的Json.Net,我有我做这个硬盘的方式一种强烈的感觉!当然还有一个更好,较少参与的方式来处理System.Text.Encoding?

I'm new to Json.Net, and I have a strong feeling that I'm doing this the hard way! Surely there is a better and less involved way to handle System.Text.Encoding?

推荐答案

使用 [ DataContract] [数据成员] 属性明确地设置其属性将在的TestClass 对象。

Use [DataContract] and [DataMember] attributes to explicity set which properties will be serialized on your TestClass objects.


  1. 从你的<$ C $省略 [数据成员] 属性C> TheEncoding 属性。

  2. 创建它被序列化UTF-8(根据 TheEncoding <值作为一个辅助属性/ code>)。包括这个属性的 [数据成员] 属性

  1. Omit the [DataMember] attribute from your TheEncoding property.
  2. Create a helper property which gets serialized as "utf-8" (depending on the value of TheEncoding). Include the [DataMember] attribute on this property.

例如:

[DataContract]
public class TestClass
{
  public Encoding TheEncoding { get; set; }

  [DataMember]
  public string TheEncodingName
  {
    get
    {
      if (this.TheEncoding == System.Text.Encoding.UTF8)
        return "utf-8";
      // TODO: More possibilities
    }
    set
    {
      if (value == "utf-8")
        this.TheEncoding = System.Text.Encoding.UTF8;
      // TODO: More possibilities
    }
  }
}

在系列化, TheEncoding 将跳过 TheEncodingName 将被替代序列化。

When serialized, TheEncoding will be skipped and TheEncodingName will be serialized instead.

这篇关于有没有更好的方式来处理与Json.Net编码值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆