据我所知,没有内置的方法可以做到这一点。
有一个关于这个主题的issue,但它已被关闭。
作者关于这个问题的一些cmets:
Json.NET 默认将整数值读取为 Int64,因为无法知道该值应该是 Int32 还是 Int64,并且 Int64 不太可能溢出。对于类型化的属性,反序列化器知道将 Int64 转换为 Int32,但是因为您的属性是无类型的,所以您得到的是 Int64。 [...] 这正是 Json.NET 的工作方式。
最简单的解决方案当然是将类型更改为Dictionary<string, int>,但我想您不仅在阅读数字,因此被object 卡住了。
另一种选择是使用 Serialization Callbacks 并将这些 Int64s 手动转换为 Int32 或创建自己的 Contract Resolver JsonConverter 并直接控制 (de-)序列化。
编辑:我创建了一个更具体的小例子。
这是一个非常基本的转换器,仅适用于您的特定字典:
public class Int32Converter : JsonConverter {
public override bool CanConvert(Type objectType) {
// may want to be less concrete here
return objectType == typeof(Dictionary<string, object>);
}
public override bool CanWrite {
// we only want to read (de-serialize)
get { return false; }
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) {
// again, very concrete
Dictionary<string, object> result = new Dictionary<string, object>();
reader.Read();
while (reader.TokenType == JsonToken.PropertyName) {
string propertyName = reader.Value as string;
reader.Read();
object value;
if (reader.TokenType == JsonToken.Integer)
value = Convert.ToInt32(reader.Value); // convert to Int32 instead of Int64
else
value = serializer.Deserialize(reader); // let the serializer handle all other cases
result.Add(propertyName, value);
reader.Read();
}
return result;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) {
// since CanWrite returns false, we don't need to implement this
throw new NotImplementedException();
}
}
您可以使用属性通过转换器或pass it as parameter 来装饰成员(反)序列化方法。这是我使用属性的示例:
[JsonObject]
public class MyObject {
[JsonConverter(typeof(Int32Converter))]
public Dictionary<string, object> Properties { get; set; }
}
这是我用来测试实现的代码:
class Program {
static void Main(string[] args) {
MyObject test = new MyObject();
test.Properties = new Dictionary<string, object>() { { "int", 15 }, { "string", "hi" }, { "number", 7 } };
Print("Original:", test);
string json = JsonConvert.SerializeObject(test);
Console.WriteLine("JSON:\n{0}\n", json);
MyObject parsed = JsonConvert.DeserializeObject<MyObject>(json);
Print("Deserialized:", parsed);
}
private static void Print(string heading, MyObject obj) {
Console.WriteLine(heading);
foreach (var kvp in obj.Properties)
Console.WriteLine("{0} = {1} of {2}", kvp.Key, kvp.Value, kvp.Value.GetType().Name);
Console.WriteLine();
}
}
没有转换器,结果将是:
Deserialized:
int = 15 of Int64
string = hi of String
number = 7 of Int64
使用转换器是:
Deserialized:
int = 15 of Int32
string = hi of String
number = 7 of Int32