1、
摘自:
public static string ToJson(object obj,bool formatjson) { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); IsoDateTimeConverter idtc = new IsoDateTimeConverter(); idtc.DateTimeFormat = "yyyy-MM-dd hh:mm:ss"; JsonSerializer serializer = new JsonSerializer(); serializer.Converters.Add(idtc); JsonWriter jw = new JsonTextWriter(sw); if (formatjson) { jw.Formatting = Formatting.Indented; } serializer.Serialize(jw, obj); return sb.ToString(); }
生成的日期格式为一字符串,这样便于客户端处理!
2、自定义反序列化
参考:
在我们需要反序列化的类和json中的数据完全匹配的情况下,使用DeserializeObject方法是最方便快速的,切忌类型要一致,否则会出现无法转换的错误。
T or = JsonConvert.DeserializeObject < T > (jsonString);
string jsonText = @"{ 2 ""short"":{ 3 ""original"":""http://www.foo.com/"", 4 ""short"":""krehqk"", 5 ""error"":{ 6 ""code"":0, 7 ""msg"":""No action taken""} 8 }"; 9 10 JObject json = JObject.Parse(jsonText); 11 12 Shortie shortie = new Shortie 13 { 14 Original = (string)json["short"]["original"], 15 Short = (string)json["short"]["short"], 16 Error = new ShortieException 17 { 18 Code = (int)json["short"]["error"]["code"], 19 ErrorMessage = (string)json["short"]["error"]["msg"] 20 } 21 }; 22 23 Console.WriteLine(shortie.Original); 24 // http://www.foo.com/ 25 26 Console.WriteLine(shortie.Error.ErrorMessage); 27 // No action taken
3、
摘自:
4、通过属性标签自定义JSON序列化
5、在线帮助