string JsonStr= JsonConvert.SerializeObject(Entity);
zB:
<br>
A a=new A(); a.Name="Elain00"; a.Hobby="eat eat"; string jsonStr=JsonConvert.SerializeObject(a);
2. JSON-Deserialisierung
string jsonstr = "jsonString";<br>Class model = JsonConvert.DeserializeObject
zB:
<br>
string JsonStr='"{\'Name\':\'Elaine00\',\'Hobby\':\'eat eat\'}"; A a=JsonConvert.DeserializeObject<a>(JsonStr);</a>
3. Zeitformatverarbeitung
<br>
IsoDateTimeConverter timeFormat = new IsoDateTimeConverter(); timeFormat.DateTimeFormat = "yyyy-MM-dd HH:mm:ss"; Response.Write(JsonConvert.SerializeObject(bll.GetModelList(strWhere), Newtonsoft.Json.Formatting.Indented, timeFormat));
4. Erweiterungsmethoden
<br>
public static class NewtonJSONHelper { public static string SerializeObject(this object obj) { return JsonConvert.SerializeObject(obj, Formatting.Indented, new JsonSerializerSettings{ ReferenceLoopHandling = ReferenceLoopHandling.Ignore}); } public static T DeserializeObject<t>(this string data) { return JsonConvert.DeserializeObject<t>(data, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }); } }</t></t>
5. Terminverarbeitung
<br>
public class LogEntry { public string Details { get; set; } public DateTime LogDate { get; set; } }public void WriteJsonDates() { LogEntry entry = new LogEntry { LogDate = new DateTime(2009, 2, 15, 0, 0, 0, DateTimeKind.Utc), Details = "Application started." }; // default as of Json.NET 4.5 string isoJson = JsonConvert.SerializeObject(entry); // {"Details":"Application started.","LogDate":"2009-02-15T00:00:00Z"} JsonSerializerSettings microsoftDateFormatSettings = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.Micro
<br>
public class LimitPropsContractResolver : DefaultContractResolver { private string[] props = null; public LimitPropsContractResolver(string[] props) { this.props = props; } protected override IList<jsonproperty> CreateProperties(Type type, MemberSerialization memberSerialization) { IList<jsonproperty> list = base.CreateProperties(type, memberSerialization); IsoDateTimeConverter iso = new IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" }; IList<jsonproperty> listWithConver = new List<jsonproperty>(); foreach (var item in list) { if (props.Contains(item.PropertyName)) { if (item.PropertyType.ToString().Contains("System.DateTime")) { item.Converter = iso; } listWithConver.Add(item); } } return listWithConver; } } }</jsonproperty></jsonproperty></jsonproperty></jsonproperty>
<br>
softDateFormat }; string microsoftJson = JsonConvert.SerializeObject(entry, microsoftDateFormatSettings); // {"Details":"Application started.","LogDate":"\/Date(1234656000000)\/"} string javascriptJson = JsonConvert.SerializeObject(entry, new JavaScriptDateTimeConverter()); // {"Details":"Application started.","LogDate":new Date(1234656000000)}}
<br>
2.JSON反序列化string jsonstr = "jsonString"; Class model = JsonConvert.DeserializeObject<class>(jsonstr); eg:string JsonStr='"{\'Name\':\'Elaine00\',\'Hobby\':\'eat eat\'}";A a=JsonConvert.DeserializeObject<a>(JsonStr);</a></class>
dient im Allgemeinen zur Werttypverarbeitung, indem jSetting.DefaultValueHandling festgelegt wird, um den Wert zu bestimmen, Der Wert ist ein Aufzählungstyp.
| ||||
Beziehen Sie beim Serialisieren und Deserialisieren den Standardwert ein |
<br>
[DefaultValue(30)] public int Age { get; set; }
Ich möchte Mitglieder mit Standardwerten beim Serialisieren ignorieren
<br>
Staff jack = new Staff { Name = "Jack", Age = 30, Gender = "Male", DepartmentName = "Personnel Department", Leader = null }; var jSetting = new JsonSerializerSettings(); jSetting.DefaultValueHandling = DefaultValueHandling.Ignore; string json = JsonConvert.SerializeObject(jack,jSetting); Console.WriteLine(json);
3. Ignorieren Sie einige Attribute
Stellen Sie zunächst die vor Json.Net-Serialisierungsmodi: OptOut und OptIn.OptOut | 默认值,类中所有公有成员会被序列化,如果不想被序列化,可以用特性JsonIgnore |
OptIn | 默认情况下,所有的成员不会被序列化,类中的成员只有标有特性JsonProperty的才会被序列化,当类的成员很多,但客户端仅仅需要一部分数据时,很有用 |
假如客户仅仅需要员工的姓名,此时
<br>
[JsonObject(Newtonsoft.Json.MemberSerialization.OptIn)] public class Staff { [JsonProperty] public string Name { get; set; } public int Age { get; set; } public string Gender { get; set; } public string DepartmentName { get; set; } public Staff Leader { get; set; } }
序列化:
<br>
Staff jack = new Staff { Name = "Jack", Age = 30, Gender = "Male", DepartmentName = "Personnel Department", Leader = null }; string json = JsonConvert.SerializeObject(jack);
结果:
如果客户不想要员工的领导信息
<br>
public class Staff { public string Name { get; set; } public int Age { get; set; } public string Gender { get; set; } public string DepartmentName { get; set; } [JsonIgnore] public Staff Leader { get; set; } }
序列化:
<br>
Staff tom = new Staff { Name = "Tome", Age = 42, Gender = "Male", DepartmentName = "Personnel Department"}; Staff jack = new Staff { Name = "Jack", Age = 30, Gender = "Male", DepartmentName = "Personnel Department", Leader = tom }; string json = JsonConvert.SerializeObject(jack); Console.WriteLine(json);
结果:
4.支持非公共成员
Json.Net序列化对象时,默认情况下仅仅序列化公有成员,如果想要非公有成员也被序列化,就要在该成员上加特性"JsonProperty"
5.日期处理
JsonConverters会在序列化和反序列化时被用到。JsonConverters允许手动对Json的控制。当Json的结构很复杂和你想改变一个类型怎么样被序列化时,这是非常有用的。当一个JsonConverters被添加到JsonSerializer时,它会检查每一要被序列化和反序列化的值,并返回CanConvert,如果为True,则JsonConverter读和写这个值;需要注意的是,虽然JsonConverter能够使你可以完全的控制Json的值,但是很多的Json.Net序列化的特性被限制,像是类型名称和引用处理。所有的JsonConvert都在命名空间 "Newtonsoft.Json.Converters"下
5.1IsoDateTimeConverter 和 JavaScriptDateTimeConverter
这是Json.Net中自带的两个处理日期的类,默认是IsoDateTimeConverter ,它的格式是"yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK".另一个是JavaScriptTimeConverter,它的格式是 "new Date(ticks)",其实返回的是一个JavaScript的Date对象.<br>有两种方式来应用JsonConverter,改变Json序列化和反序列化的行为.
5.1.1如果你要序列化的日期格式是统一的,可以考虑如下方式
假设我们为员工添加两个日期类型的成员,出生日期和入职日期
<br>
public class Staff { public string Name { get; set; } public int Age { get; set; } public string Gender { get; set; } public string DepartmentName { get; set; } public Staff Leader { get; set; } public DateTime BirthDate { get; set; } public DateTime EmploymentDate { get; set; } }
我们的客户要求日期类型的成员返回javascript的日期对象
<br>
Staff jack = new Staff { Name = "Jack", Age = 30, Gender = "Male", DepartmentName = "Personnel Department", BirthDate = new DateTime(1982,2,12), EmploymentDate = new DateTime(2010,12,12) }; string json = JsonConvert.SerializeObject(jack,new JavaScriptDateTimeConverter()); Console.WriteLine(json);
结果:
5.1.2如果想要不同的日期类型成员序列化后,以不同的形式显示.
现在我们的客户要求出生日期以"ISO"标准日期格式返回,入职日期以Javascript的Date对象格式返回,修改我们的员工类
<br>
public class Staff { public string Name { get; set; } public int Age { get; set; } public string Gender { get; set; } public string DepartmentName { get; set; } public Staff Leader { get; set; } [JsonConverter(typeof(IsoDateTimeConverter))] public DateTime BirthDate { get; set; } [JsonConverter(typeof(JavaScriptDateTimeConverter))] public DateTime EmploymentDate { get; set; } }
是的,通过特性"JsonConverter"来实现差异化的<br>序列化:
<br>
Staff jack = new Staff { Name = "Jack", Age = 30, Gender = "Male", DepartmentName = "Personnel Department", BirthDate = new DateTime(1982,2,12), EmploymentDate = new DateTime(2010,12,12) }; string json = JsonConvert.SerializeObject(jack); Console.WriteLine(json);
结果:
5.2自定义日期格式
客户现在提出要求,希望得到的日期格式是符合中国人习惯的格式.要求返回的格式是"2012年4月20日".挑战来了,没有挑战就没有进步,我喜欢挑战.光说是没有用的!先分析一下怎么解决这个问题.我考虑了两种思路.<br> 思路一:<br>研究了一下上面两个日期处理类,发现他们都是继承了基类"DateTimeConverterBase",所以我们可以参考"IsoDatetimeConverter"的实现方式,自己新建一个处理日期格式的转换器类.这种方式的缺点是可能要花大量的时间去研究,比较费时费力.优点就是可以对日期格式随心所欲的控制.<br> 思路二:<br>我又研究了一下"IsoDatetimeConverter",发现它的日期格式其实是由于内部DefaultDateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK"导致,而它也提供了修改日期样式的属性"DateTimeFormat",只要我们按照这种格式来写就OK了.
<br>
Staff jack = new Staff { Name = "Jack", Age = 30, Gender = "Male", DepartmentName = "Personnel Department", BirthDate = new DateTime(1982,2,12), EmploymentDate = new DateTime(2010,12,12) }; IsoDateTimeConverter dtConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy'年'MM'月'dd'日'" }; string json = JsonConvert.SerializeObject(jack,dtConverter); Console.WriteLine(json);
结果:
6.FAQ
1.如何自定义序列化的字段名称?
默认情况下,Json.Net序列化后结果中的字段名称和类中属性的名称一致.如果想自定义序列化后的字段名称,可以使用JsonProperty.例如:
<br>
public class Person { public int Id { get; set; } public string Name { get; set; } }
默认序列化的结果为: {"Id":1,"Name":"杨过"},如果不想用默认的字段名称,可以使用如下方式:
<br>
public class Person { [JsonProperty(PropertyName = "PersonId")] public int Id { get; set; } [JsonProperty(PropertyName = "PersonName")] public string Name { get; set; } }
这样序列化的结果为:{"PersonId":1,"PersonName":"杨过"}
Das obige ist der detaillierte Inhalt vonNewtonsoft.Json-Serialisierungs- und Deserialisierungszeitformat. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!