对返回的json数据重写格式,用特性JsonConverter

继承JsonConverter特性

    public class ObjJsonConverter<T> : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(T);
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType.Equals(JsonToken.String))
            {
                string data = reader.Value.ToString();//读取字符串,然后解密


                JsonReader jr = new JsonTextReader(new StringReader(data));
                if (data.Substring(0, 1).ToString() == "[")//是数组
                {
                    JArray jObj = JArray.Load(jr);
                    var obj = serializer.Deserialize<T>(jObj.CreateReader());
                    return obj;
                }
                else
                {
                    JObject jObj = JObject.Load(jr);
                    var obj = serializer.Deserialize<T>(jObj.CreateReader());
                    return obj;
                }
            }
            else if (reader.TokenType.Equals(JsonToken.StartArray))//数组的时候
            {
                List<string> strs = new List<string>();
                reader.Read();
                while (!reader.TokenType.Equals(JsonToken.EndArray))//判断读取是否结束
                {
                    JObject jArray = JObject.Load(reader);
                    strs.Add(jArray.ToJson());
                    reader.Read();
                }
                string newjs = $"[{string.Join(",", strs)}]";
                JsonReader jr = new JsonTextReader(new StringReader(newjs));
                var obj = serializer.Deserialize<T>(jr);
                return obj;
            }
            else
            {
                reader.Read();//不是数组
                JObject jArray = JObject.Load(reader);
                var obj = serializer.Deserialize<T>(jArray.CreateReader());
                return obj;
            }
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            writer.WriteValue(value);
        }
    }

 

 使用方法

 [JsonConverter(typeof(ObjJsonConverter<List<RegisterData>>))]
 public List<RegisterData> data { get; set; }

 

posted @ 2021-11-03 14:54  世人皆萌  阅读(351)  评论(0编辑  收藏  举报