據我所知,沒有內置的方法來做到這一點。
在這個問題上有一個issue,但它已經關閉。 從筆者對這個問題的一些意見:
Json.NET默認讀取整數值作爲Int64的,因爲沒有辦法知道的值是否應的Int32或Int64類型,並Int64的是不太可能溢出。對於一個類型化的屬性,反序列化器知道將Int64轉換爲Int32,但是因爲你的屬性是無類型的,所以你得到了一個Int64。 [...]這只是Json.NET的工作方式。課的的
最簡單的辦法是將類型更改爲Dictionary<string, int>
,但我想你不僅是閱讀數字和因此被套牢object
。
另一種選擇是要麼使用Serialization Callbacks和手動那些Int64
秒值進行轉換,以Int32
或創建自己的Contract ResolverJsonConverter和直接控制(去)序列化。
編輯:我創建了一個小例子更加具體。
這是一個非常基本的轉換器,只用你的specifc字典的工作原理:
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
評論整理:OP是知道POCO選項,但並不想這樣做 –