.NET 中json格式化和字段重命名的使用
1.通用的扩展类
public static partial class Extensions
{
/// <summary>
/// 将object转换为long,若转换失败,则返回0。不抛出异常。
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static long ParseToLong(this object obj)
{
try
{
return long.Parse(obj.ToString());
}
catch
{
return 0L;
}
}
public static string ParseToString(this object obj)
{
try
{
if (obj == null)
{
return string.Empty;
}
else
{
return obj.ToString();
}
}
catch
{
return string.Empty;
}
}
public static DateTime ParseToDateTime(this string str)
{
try
{
if (string.IsNullOrWhiteSpace(str))
{
return DateTime.MinValue;
}
if (str.Contains("-") || str.Contains("/"))
{
return DateTime.Parse(str);
}
else
{
int length = str.Length;
switch (length)
{
case 4:
return DateTime.ParseExact(str, "yyyy", System.Globalization.CultureInfo.CurrentCulture);
case 6:
return DateTime.ParseExact(str, "yyyyMM", System.Globalization.CultureInfo.CurrentCulture);
case 8:
return DateTime.ParseExact(str, "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture);
case 10:
return DateTime.ParseExact(str, "yyyyMMddHH", System.Globalization.CultureInfo.CurrentCulture);
case 12:
return DateTime.ParseExact(str, "yyyyMMddHHmm", System.Globalization.CultureInfo.CurrentCulture);
case 14:
return DateTime.ParseExact(str, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture);
default:
return DateTime.ParseExact(str, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture);
}
}
}
catch
{
return DateTime.MinValue;
}
}
}
2.json格式化转换器,继承JsonConverter 重写里面的方法,具体实现如下
public class StringJsonConverter : JsonConverter
{
public StringJsonConverter() { }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
return reader.Value.ParseToLong();
}
public override bool CanConvert(Type objectType)
{
return true;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if (value == null)
{
writer.WriteNull();
return;
}
string sValue = value.ToString();
writer.WriteValue(sValue);
}
}
/// <summary>
/// DateTime类型序列化的时候,转成指定的格式
/// </summary>
public class DateTimeJsonConverter : JsonConverter
{
public DateTimeJsonConverter() { }
public override bool CanConvert(Type objectType)
{
return true;
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
return reader.Value.ParseToString().ParseToDateTime();
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if (value == null)
{
writer.WriteNull();
return;
}
DateTime? dt = value as DateTime?;
if (dt == null)
{
writer.WriteNull();
return;
}
writer.WriteValue(dt.Value.ToString("yyyy-MM-dd HH:mm:ss"));
}
}
3.定义一个实体,并在特性上加上转换器,里面还有个[JsonProperty(“Address”)],当传进来的json是Address,他会和实体的DetailsAddress对应,当然DetailsAddress 转换为json的字段也是显示成Address
public class BaseArea
{
[JsonProperty("Address")]
public string DetailsAddress { get; set; }
/// <summary>
/// 省份ID
/// </summary>
/// <returns></returns>
[JsonConverter(typeof(StringJsonConverter))]
public long? ProvinceId { get; set; }
/// <summary>
/// 城市ID
/// </summary>
/// <returns></returns>
[JsonConverter(typeof(StringJsonConverter))]
public long? CityId { get; set; }
/// <summary>
/// 区域ID
/// </summary>
/// <returns></returns>
[JsonConverter(typeof(StringJsonConverter))]
public long? CountyId { get; set; }
public string ProvinceName { get; set; }
public string CityName { get; set; }
public string CountryName { get; set; }
public string AreaId { get; set; }
[JsonConverter(typeof(DateTimeJsonConverter))]
public DateTime CreateDate { get; set; }
}
4 调用demo,把字段为long的转为string,时间格式化转为string类型
static void Main(string[] args)
{
BaseArea baseArea = new BaseArea {
CountyId = 12345678908765,
AreaId = "12344",
CityName = "深圳",
CreateDate = DateTime.Now,
CountryName = "广东",
ProvinceId = 123456667865555555 ,
ProvinceName="广东省",
CityId=12345666666666688
,DetailsAddress="西头新村"
};
string json= JsonConvert.SerializeObject(baseArea);
var t= JsonConvert.DeserializeObject<BaseArea>(json);
}