如果您事先知道您的 4 个标准字符串,您可以使用String.Intern()
(或者只是在某处将它们声明为字符串文字 - 这样做)然后使用以下自定义JsonConverter
将所有 JSON 字符串文字转换为它们的实习值(如果找到) :
public class InternedStringConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(string);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
return null;
var s = reader.TokenType == JsonToken.String ? (string)reader.Value : (string)JToken.Load(reader); // Check is in case the value is a non-string literal such as an integer.
return String.IsInterned(s) ?? s;
}
public override bool CanWrite { get { return false; } }
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
这可以通过序列化程序设置全局应用:
var settings = new JsonSerializerSettings { Converters = new [] { new InternedStringConverter() } };
var root = JsonConvert.DeserializeObject<RootObject>(jsonString, settings);
您还可以使用以下命令将其应用于特定的字符串集合JsonPropertyAttribute.ItemConverterType
:
public class Group
{
[JsonProperty(ItemConverterType = typeof(InternedStringConverter))]
public List<string> StandardStrings { get; set; }
}
如果您事先不知道这 4 个字符串,则可以创建一个转换器,在读取字符串时对其进行实习:
public class AutoInterningStringConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
// CanConvert is not called when a converter is applied directly to a property.
throw new NotImplementedException("AutoInterningStringConverter should not be used globally");
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
return null;
var s = reader.TokenType == JsonToken.String ? (string)reader.Value : (string)JToken.Load(reader); // Check is in case the value is a non-string literal such as an integer.
return String.Intern(s);
}
public override bool CanWrite { get { return false; } }
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
但是,我强烈建议不要在全局范围内使用它,因为您最终可能会在内部字符串表中添加大量字符串。相反,仅将其应用于您确信包含少量唯一字符串重复的特定字符串集合:
public class Group
{
[JsonProperty(ItemConverterType = typeof(AutoInterningStringConverter))]
public List<string> StandardStrings { get; set; }
}
更新
从您更新的问题中,我看到您具有具有标准值的字符串属性,而不是具有标准值的字符串集合。因此,您将[JsonConverter(typeof(AutoInterningStringConverter))]
在每个上使用:
public class Group
{
[JsonConverter(typeof(AutoInterningStringConverter))]
public string groupName { get; set; }
public string code { get; set; }
}