发布:2023/3/24 14:45:35作者:管理员 来源:本站 浏览次数:529
public class JSON2DictConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
bool match = (objectType == typeof(object));
return match;
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.StartObject
|| reader.TokenType == JsonToken.Null)
{
JToken token = JToken.Load(reader);
string json = token.ToString();
Dictionary<string,object> dict = JsonConvert.DeserializeObject<Dictionary<string, object>>(json, this);
return dict;
}
if (reader.TokenType == JsonToken.StartArray)
{
JToken token = JToken.Load(reader);
string json = token.ToString();
List<object> list = JsonConvert.DeserializeObject<List<object>>(json, this);
return list;
}
return serializer.Deserialize(reader);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
使用
Dictionary<string, object> dict = JsonConvert.DeserializeObject<Dictionary<string, object>>(json, new GameCore.JSON2DictConverter());
or
Dictionary<List<object> dict = JsonConvert.DeserializeObject<List<object>>(json, new GameCore.JSON2DictConverter());