本人使用的VS2010 需要下载的是 :Json50r6.zip C#5使用;
网上还有一个版本:Newtonsoft.Json.rar 这个只有在C#6才能使用;
下载解压以后应用看自己的.net版本引用,本人引用的是
使用很方便:
反序列化:
string jsonText = "{\"zone\":\"海淀\",\"zone_en\":\"haidian\"}";
JObject jo = (JObject)JsonConvert.DeserializeObject(jsonText);
string zone = jo["zone"].ToString();
string zone_en = jo["zone_en"].ToString();
//LogUtil.LogInfo(zone);
//LogUtil.LogInfo(zone_en);
序列化:
首先新建一个类
class a
{
/// <summary>
/// 定义实体转换名字
/// </summary>
[JsonProperty(PropertyName = "CName")]
public string s;
[JsonIgnore]//忽略的属性
public string d;
[JsonConverter(typeof(ChinaDateTimeConverter))]
[JsonProperty]//支持非公共属性
DateTime dd;
public DateTime dt;
[JsonConverter(typeof(BoolConvert))]
public bool b;
[DefaultValue(10)]//默认值
int x;
}
里面涉及到了时间格式的转化和bool类型的转换(true转为是,false转为否),需要重写两个类:
//时间类转换
public class ChinaDateTimeConverter : DateTimeConverterBase
{
private static IsoDateTimeConverter dtConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd" };//可以自己修改
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
return dtConverter.ReadJson(reader, objectType, existingValue, serializer);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
dtConverter.WriteJson(writer, value, serializer);
}
}
//bool类转化
public class BoolConvert : JsonConverter
{
private string[] arrBString { get; set; }
public BoolConvert()
{
arrBString = "是,否".Split(',');
}
/// <summary>
/// 构造函数
/// </summary>
/// <param name="BooleanString">将bool值转换成的字符串值</param>
public BoolConvert(string BooleanString)
{
if (string.IsNullOrEmpty(BooleanString))
{
throw new ArgumentNullException();
}
arrBString = BooleanString.Split(',');
if (arrBString.Length != 2)
{
throw new ArgumentException("BooleanString格式不符合规定");
}
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
bool isNullable = IsNullableType(objectType);
Type t = isNullable ? Nullable.GetUnderlyingType(objectType) : objectType;
if (reader.TokenType == JsonToken.Null)
{
if (!IsNullableType(objectType))
{
throw new Exception(string.Format("不能转换null value to {0}.", objectType));
}
return null;
}
try
{
if (reader.TokenType == JsonToken.String)
{
string boolText = reader.Value.ToString();
if (boolText.Equals(arrBString[0], StringComparison.OrdinalIgnoreCase))
{
return true;
}
else if (boolText.Equals(arrBString[1], StringComparison.OrdinalIgnoreCase))
{
return false;
}
}
if (reader.TokenType == JsonToken.Integer)
{
//数值
return Convert.ToInt32(reader.Value) == 1;
}
}
catch (Exception ex)
{
throw new Exception(string.Format("Error converting value {0} to type '{1}'", reader.Value, objectType));
}
throw new Exception(string.Format("Unexpected token {0} when parsing enum", reader.TokenType));
}
/// <summary>
/// 判断是否为Bool类型
/// </summary>
/// <param name="objectType">类型</param>
/// <returns>为bool类型则可以进行转换</returns>
public override bool CanConvert(Type objectType)
{
return true;
}
public bool IsNullableType(Type t)
{
if (t == null)
{
throw new ArgumentNullException("t");
}
return (t.BaseType.FullName == "System.ValueType" && t.GetGenericTypeDefinition() == typeof(Nullable<>));
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if (value == null)
{
writer.WriteNull();
return;
}
bool bValue = (bool)value;
if (bValue)
{
writer.WriteValue(arrBString[0]);
}
else
{
writer.WriteValue(arrBString[1]);
}
}
}
然后实例化类:
a d = new a();
d.s = "1";
d.d = "2";
d.dt = DateTime.Now;
d.b = false;
///全局设置
JsonSerializerSettings setting = new JsonSerializerSettings();
setting.DateFormatHandling = DateFormatHandling.MicrosoftDateFormat;
setting.DateFormatString = "yyyy-MM-dd HH:mm:ss";
setting.NullValueHandling = NullValueHandling.Ignore; //忽略空值
setting.Converters.Add(new BoolConvert("是,否"));
string js = JsonConvert.SerializeObject(d, Formatting.Indented, setting);