当前位置: 首页 > 工具软件 > Jsonnet > 使用案例 >

JsonNet 读取转换器 Json文本转Dictionary

明利
2023-12-01

	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());
 类似资料: