C# 序列化大小写 序列化对象为大小写 JsonConvert.SerializeObject
关于C#序列化Json对象
框架:.Net
插件:Newtonsoft.Json
最近有人问我序列化对象还区分大小写? 我当时心想我都是通过Bejson 格式化然后转换为C# 类然后直接复制。
没有关心过序列化成什么大小写。因为这样的话可以保持一致。
直到有人问我才自己研究了一下。
如下:
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; using System.Xml; using Newtonsoft.Json.Serialization; using Formatting = Newtonsoft.Json.Formatting; using static System.Net.Mime.MediaTypeNames; using System.Text.Json; using System.Xml.Linq; using static System.Threading.Thread; using static 序列化.Program; namespace 序列化 { internal class Program { private static void Main() { //定义匿名对象 var user = new { name = "john", age = 19 }; var user1 = new { NAME = "JOHN", AGE = 19 }; var user2 = new { Name = "john", Age = 19 }; var user3 = new { namE = "john", agE = 19 }; var user4 = new { naMe = "john", aGe = 19 }; Action(user); Action(user1); Action(user2); Action(user3); Action(user4); Console.WriteLine("分割"); Action1(user); Action1(user1); Action1(user2); Action1(user3); Action1(user4); Console.WriteLine("分割"); var person = new Person { Age = 10, Name = "john" }; Action2(person); var person1 = new Person1 { Age = 10, Name = "john" }; Action2(person1); Console.ReadKey(); } public static void Action(dynamic obj) { var serializerSettings = new JsonSerializerSettings { // 设置为驼峰命名 ContractResolver = new CamelCasePropertyNamesContractResolver() }; //序列化成字符串 var userStr = JsonConvert.SerializeObject(obj, Formatting.None, serializerSettings); //输出字符串 Console.WriteLine($"方法一{userStr}"); } public static void Action1(dynamic obj) { //ToTitleCase 会把头一个字母大写 弊端:如果你的变量值为英文则也会变成大写 var monstrous = CurrentThread.CurrentCulture.TextInfo.ToTitleCase(JsonConvert.SerializeObject(obj)); //ToUpper 将所有文本变成大写 var monstrous1 = CurrentThread.CurrentCulture.TextInfo.ToUpper(JsonConvert.SerializeObject(obj)); //ToUpper 将所有文本变成大写 var monstrous2 = CurrentThread.CurrentCulture.TextInfo.ToLower(JsonConvert.SerializeObject(obj)); Console.WriteLine($"方法二{monstrous}{monstrous1}{monstrous2}"); } public static void Action2(Person obj) { //Formatting.Indented 使用子类型对象 var json = JsonConvert.SerializeObject(obj, Formatting.Indented); Console.WriteLine($"方法三{json}"); } public static void Action2(Person1 obj) { var json = JsonConvert.SerializeObject(obj, Formatting.Indented); Console.WriteLine($"方法三{json}"); } [DataContract] public class Person { [DataMember(Name = "AGE")] public int Age { get; set; } [DataMember(Name = "NAME")] public string Name { get; set; } } [DataContract] public class Person1 { [DataMember(Name = "aGe")] public int Age { get; set; } [DataMember(Name = "NaME")] public string Name { get; set; } } } }
以上就是我自己写的一个Demo来搞序列化对象成为我想要的对象大小写。
输出如下:
我个人认为方法三才是真正能实现我的需求,其他两种都有相对应的弊端。
也可能方法用法不对。也希望大神能多多指教。