Net.Json 常用例子

#JsonConvert 例子

內容主要都是官方的例子,加上一些中文註釋而已。 主要方便自己查詢,分享一份出來.

參考文檔:
https://www.newtonsoft.com/json/help/html/Introduction.htm

##JsonConver序列化
    Product product = new Product();
    
    product.Name = "Apple";
    product.ExpiryDate = new DateTime(2008, 12, 28);
    product.Price = 3.99M;
    product.Sizes = new string[] { "Small", "Medium", "Large" };
    
    string output = JsonConvert.SerializeObject(product);
    //{
    //  "Name": "Apple",
    //  "ExpiryDate": "2008-12-28T00:00:00",
    //  "Price": 3.99,
    //  "Sizes": [
    //    "Small",
    //    "Medium",
    //    "Large"
    //  ]
    //}
    
    Product deserializedProduct = JsonConvert.DeserializeObject<Product>(output);

##JsonSerializer
如果需要對對象序列化進行更多的控制。JsonSerializer能夠支持Json讀寫流( JsonTextReader and JsonTextWriter)

    Product product = new Product();
    product.ExpiryDate = new DateTime(2008, 12, 28);
    
    JsonSerializer serializer = new JsonSerializer();
    serializer.Converters.Add(new JavaScriptDateTimeConverter());
    serializer.NullValueHandling = NullValueHandling.Ignore;
    
    using (StreamWriter sw = new StreamWriter(@"c:\json.txt"))
    using (JsonWriter writer = new JsonTextWriter(sw))
    {
        serializer.Serialize(writer, product);
        // {"ExpiryDate":new Date(1230375600000),"Price":0}
    }

## Json特性

    JsonObjectAttribute - 控制Net.Json序列化對象

    JsonArrayAttribute - 控制Net.Json序列化Array對象

    JsonDictionaryAttribute - 控制Net.Json序列化Dictionary對象

    JsonPropertyAttribute - 控制Net.Json這些屬性、字段需要序列化

    JsonConverterAttribute - 控制classes or fields and properties指定JsonConverter 進行序列化

    JsonExtensionDataAttribute - 將不匹配的成員寫入指定的容器中,具體可以看例子

    JsonConstructorAttribute 指定反序列化時指定構造函數創建類


## Json回調

    public class SerializationEventTestObject
    {
        // 2222
        // This member is serialized and deserialized with no change.
        public int Member1 { get; set; }
    
        // The value of this field is set and reset during and 
        // after serialization.
        public string Member2 { get; set; }
    
        // This field is not serialized. The OnDeserializedAttribute 
        // is used to set the member value after serialization.
        [JsonIgnore]
        public string Member3 { get; set; }
    
        // This field is set to null, but populated after deserialization.
        public string Member4 { get; set; }
    
        public SerializationEventTestObject()
        {
            Member1 = 11;
            Member2 = "Hello World!";
            Member3 = "This is a nonserialized value";
            Member4 = null;
        }
    
        [OnSerializing]
        internal void OnSerializingMethod(StreamingContext context)
        {
            Member2 = "This value went into the data file during serialization.";
        }
    
        [OnSerialized]
        internal void OnSerializedMethod(StreamingContext context)
        {
            Member2 = "This value was reset after serialization.";
        }
    
        [OnDeserializing]
        internal void OnDeserializingMethod(StreamingContext context)
        {
            Member3 = "This value was set during deserialization";
        }
    
        [OnDeserialized]
        internal void OnDeserializedMethod(StreamingContext context)
        {
            Member4 = "This value was set after deserialization.";
        }
    }

###測試代碼
    SerializationEventTestObject obj = new SerializationEventTestObject();
    
    Console.WriteLine(obj.Member1);
    // 11
    Console.WriteLine(obj.Member2);
    // Hello World!
    Console.WriteLine(obj.Member3);
    // This is a nonserialized value
    Console.WriteLine(obj.Member4);
    // null
    
    string json = JsonConvert.SerializeObject(obj, Formatting.Indented);
    // {
    //   "Member1": 11,
    //   "Member2": "This value went into the data file during serialization.",
    //   "Member4": null
    // }
    
    Console.WriteLine(obj.Member1);
    // 11
    Console.WriteLine(obj.Member2);
    // This value was reset after serialization.
    Console.WriteLine(obj.Member3);
    // This is a nonserialized value
    Console.WriteLine(obj.Member4);
    // null
    
    obj = JsonConvert.DeserializeObject<SerializationEventTestObject>(json);
    
    Console.WriteLine(obj.Member1);
    // 11
    Console.WriteLine(obj.Member2);
    // This value went into the data file during serialization.
    Console.WriteLine(obj.Member3);
    // This value was set during deserialization
    Console.WriteLine(obj.Member4);
    // This value was set after deserialization.


## Json 錯誤處理

###方法1 JsonConvert 委託

    List<string> errors = new List<string>();
    
    List<DateTime> c = JsonConvert.DeserializeObject<List<DateTime>>(@"[
          '2009-09-09T00:00:00Z',
          'I am not a date and will error!',
          [
            1
          ],
          '1977-02-20T00:00:00Z',
          null,
          '2000-12-01T00:00:00Z'
        ]",
        new JsonSerializerSettings
        {
            Error = delegate(object sender, ErrorEventArgs args)
            {
                errors.Add(args.ErrorContext.Error.Message);
                args.ErrorContext.Handled = true;
            },
            Converters = { new IsoDateTimeConverter() }
        });
    
    // 2009-09-09T00:00:00Z
    // 1977-02-20T00:00:00Z
    // 2000-12-01T00:00:00Z
    
    // The string was not recognized as a valid DateTime. There is a unknown word starting at index 0.
    // Unexpected token parsing date. Expected String, got StartArray.
    // Cannot convert null value to System.DateTime.


###方法2 JsonSerializer 委託
    List<string> errors = new List<string>();
    
    JsonSerializer serializer = new JsonSerializer();
    serializer.Error += delegate(object sender, ErrorEventArgs args)
    {
        // only log an error once
        if (args.CurrentObject == args.ErrorContext.OriginalObject)
        {
            errors.Add(args.ErrorContext.Error.Message);
        }
    };

###方法3 OnErrorAttribute
    public class PersonError
    {
        private List<string> _roles;
    
        public string Name { get; set; }
        public int Age { get; set; }
    
        public List<string> Roles
        {
            get
            {
                if (_roles == null)
                {
                    throw new Exception("Roles not loaded!");
                }
    
                return _roles;
            }
            set { _roles = value; }
        }
    
        public string Title { get; set; }
             [OnError]         internal void OnError(StreamingContext context, ErrorContext errorContext)         {             errorContext.Handled = true;         }     }     PersonError person = new PersonError     {         Name = "George Michael Bluth",         Age = 16,         Roles = null,         Title = "Mister Manager"     };          string json = JsonConvert.SerializeObject(person, Formatting.Indented);          Console.WriteLine(json);     //{     //  "Name": "George Michael Bluth",     //  "Age": 16,     //  "Title": "Mister Manager"     //} ## 自定義轉換器CustomCreationConverter     public interface IPerson     {         string FirstName { get; set; }         string LastName { get; set; }         DateTime BirthDate { get; set; }     }          public class Employee : IPerson     {         public string FirstName { get; set; }         public string LastName { get; set; }         public DateTime BirthDate { get; set; }              public string Department { get; set; }         public string JobTitle { get; set; }     }          public class PersonConverter : CustomCreationConverter<IPerson>     {         public override IPerson Create(Type objectType)         {             return new Employee();         }     } ----------     //[     //  {     //    "FirstName": "Maurice",     //    "LastName": "Moss",     //    "BirthDate": "1981-03-08T00:00Z",     //    "Department": "IT",     //    "JobTitle": "Support"     //  },     //  {     //    "FirstName": "Jen",     //    "LastName": "Barber",     //    "BirthDate": "1985-12-10T00:00Z",     //    "Department": "IT",     //    "JobTitle": "Manager"     //  }     //]          List<IPerson> people = JsonConvert.DeserializeObject<List<IPerson>>(json, new PersonConverter());          IPerson person = people[0];          Console.WriteLine(person.GetType());     // Newtonsoft.Json.Tests.Employee          Console.WriteLine(person.FirstName);     // Maurice          Employee employee = (Employee)person;          Console.WriteLine(employee.JobTitle);     // Support ## 序列化跟蹤日誌     Staff staff = new Staff();     staff.Name = "Arnie Admin";     staff.Roles = new List<string> { "Administrator" };     staff.StartDate = new DateTime(2000, 12, 12, 12, 12, 12, DateTimeKind.Utc);          ITraceWriter traceWriter = new MemoryTraceWriter();          JsonConvert.SerializeObject(         staff,         new JsonSerializerSettings { TraceWriter = traceWriter, Converters = { new JavaScriptDateTimeConverter() } });          Console.WriteLine(traceWriter);     // 2012-11-11T12:08:42.761 Info Started serializing Newtonsoft.Json.Tests.Serialization.Staff. Path ''.     // 2012-11-11T12:08:42.785 Info Started serializing System.DateTime with converter Newtonsoft.Json.Converters.JavaScriptDateTimeConverter. Path 'StartDate'.     // 2012-11-11T12:08:42.791 Info Finished serializing System.DateTime with converter Newtonsoft.Json.Converters.JavaScriptDateTimeConverter. Path 'StartDate'.     // 2012-11-11T12:08:42.797 Info Started serializing System.Collections.Generic.List`1[System.String]. Path 'Roles'.     // 2012-11-11T12:08:42.798 Info Finished serializing System.Collections.Generic.List`1[System.String]. Path 'Roles'.     // 2012-11-11T12:08:42.799 Info Finished serializing Newtonsoft.Json.Tests.Serialization.Staff. Path ''.     // 2013-05-18T21:38:11.255 Verbose Serialized JSON:      // {     //   "Name": "Arnie Admin",     //   "StartDate": new Date(     //     976623132000     //   ),     //   "Roles": [     //     "Administrator"     //   ]     // } ### 自定義序列化跟蹤日誌     public class NLogTraceWriter : ITraceWriter     {         private static readonly Logger Logger = LogManager.GetLogger("NLogTraceWriter");              public TraceLevel LevelFilter         {             // trace all messages. nlog can handle filtering             get { return TraceLevel.Verbose; }         }              public void Trace(TraceLevel level, string message, Exception ex)         {             LogEventInfo logEvent = new LogEventInfo             {                 Message = message,                 Level = GetLogLevel(level),                 Exception = ex             };                  // log Json.NET message to NLog             Logger.Log(logEvent);         }              private LogLevel GetLogLevel(TraceLevel level)         {             switch (level)             {                 case TraceLevel.Error:                     return LogLevel.Error;                 case TraceLevel.Warning:                     return LogLevel.Warn;                 case TraceLevel.Info:                     return LogLevel.Info;                 case TraceLevel.Off:                     return LogLevel.Off;                 default:                     return LogLevel.Trace;             }         }     } #    LINQ to JSON ##解析對象      JObject o = JObject.Parse(@"{        'CPU': 'Intel',        'Drives': [          'DVD read/writer',          '500 gigabyte hard drive'        ]      }");            string cpu = (string)o["CPU"];      // Intel            string firstDrive = (string)o["Drives"][0];      // DVD read/writer            IList<string> allDrives = o["Drives"].Select(t => (string)t).ToList();      // DVD read/writer      // 500 gigabyte hard drive ##解析數組對象     string json = @"[       'Small',       'Medium',       'Large'     ]";          JArray a = JArray.Parse(json); ## 創建Json     JArray array = new JArray();     JValue text = new JValue("Manual text");     JValue date = new JValue(new DateTime(2000, 5, 23));          array.Add(text);     array.Add(date);          string json = array.ToString();     // [     //   "Manual text",     //   "2000-05-23T00:00:00"     // ] ## Linq 創建Json     List<Post> posts = GetPosts();          JObject rss =         new JObject(             new JProperty("channel",                 new JObject(                     new JProperty("title", "James Newton-King"),                     new JProperty("link", "http://james.newtonking.com"),                     new JProperty("description", "James Newton-King's blog."),                     new JProperty("item",                         new JArray(                             from p in posts                             orderby p.Title                             select new JObject(                                 new JProperty("title", p.Title),                                 new JProperty("description", p.Description),                                 new JProperty("link", p.Link),                                 new JProperty("category",                                     new JArray(                                         from c in p.Categories                                         select new JValue(c)))))))));          Console.WriteLine(rss.ToString());          //{     //  "channel": {     //    "title": "James Newton-King",     //    "link": "http://james.newtonking.com",     //    "description": "James Newton-King\'s blog.",     //    "item": [     //      {     //        "title": "Json.NET 1.3 + New license + Now on CodePlex",     //        "description": "Annoucing the release of Json.NET 1.3, the MIT license and being available on CodePlex",     //        "link": "http://james.newtonking.com/projects/json-net.aspx",     //        "category": [     //          "Json.NET",     //          "CodePlex"     //        ]     //      },     //      {     //        "title": "LINQ to JSON beta",     //        "description": "Annoucing LINQ to JSON",     //        "link": "http://james.newtonking.com/projects/json-net.aspx",     //        "category": [     //          "Json.NET",     //          "LINQ"     //        ]     //      }     //    ]     //  }     //} ## 從一個對象創建Json     JObject o = JObject.FromObject(new     {         channel = new         {             title = "James Newton-King",             link = "http://james.newtonking.com",             description = "James Newton-King's blog.",             item =                 from p in posts                 orderby p.Title                 select new                 {                     title = p.Title,                     description = p.Description,                     link = p.Link,                     category = p.Categories                 }         }     }); ## 查詢Json值     string json = @"{       'channel': {         'title': 'James Newton-King',         'link': 'http://james.newtonking.com',         'description': 'James Newton-King\'s blog.',         'item': [           {             'title': 'Json.NET 1.3 + New license + Now on CodePlex',             'description': 'Annoucing the release of Json.NET 1.3, the MIT license and the source on CodePlex',             'link': 'http://james.newtonking.com/projects/json-net.aspx',             'categories': [               'Json.NET',               'CodePlex'             ]           },           {             'title': 'LINQ to JSON beta',             'description': 'Annoucing LINQ to JSON',             'link': 'http://james.newtonking.com/projects/json-net.aspx',             'categories': [               'Json.NET',               'LINQ'             ]           }         ]       }     }";          JObject rss = JObject.Parse(json);          string rssTitle = (string)rss["channel"]["title"];     // James Newton-King          string itemTitle = (string)rss["channel"]["item"][0]["title"];     // Json.NET 1.3 + New license + Now on CodePlex          JArray categories = (JArray)rss["channel"]["item"][0]["categories"];     // ["Json.NET", "CodePlex"]          IList<string> categoriesText = categories.Select(c => (string)c).ToList();     // Json.NET     // CodePlex ## Linq查詢     var postTitles =         from p in rss["channel"]["item"]         select (string)p["title"];          foreach (var item in postTitles)     {         Console.WriteLine(item);     }          //LINQ to JSON beta     //Json.NET 1.3 + New license + Now on CodePlex          var categories =         from c in rss["channel"]["item"].SelectMany(i => i["categories"]).Values<string>()         group c by c         into g         orderby g.Count() descending         select new { Category = g.Key, Count = g.Count() };          foreach (var c in categories)     {         Console.WriteLine(c.Category + " - Count: " + c.Count);     }          //Json.NET - Count: 2     //LINQ - Count: 1     //CodePlex - Count: 1 ## 使用LInq反序列化     string jsonText = @"{       'short': {         'original': 'http://www.foo.com/',         'short': 'krehqk',         'error': {           'code': 0,           'msg': 'No action taken'         }       }     }";          JObject json = JObject.Parse(jsonText);          Shortie shortie = new Shortie     {         Original = (string)json["short"]["original"],         Short = (string)json["short"]["short"],         Error = new ShortieException         {             Code = (int)json["short"]["error"]["code"],             ErrorMessage = (string)json["short"]["error"]["msg"]         }     };          Console.WriteLine(shortie.Original);     // http://www.foo.com/          Console.WriteLine(shortie.Error.ErrorMessage);     // No action taken ## SelectToken查詢Json     JObject o = JObject.Parse(@"{       'Stores': [         'Lambton Quay',         'Willis Street'       ],       'Manufacturers': [         {           'Name': 'Acme Co',           'Products': [             {               'Name': 'Anvil',               'Price': 50             }           ]         },         {           'Name': 'Contoso',           'Products': [             {               'Name': 'Elbow Grease',               'Price': 99.95             },             {               'Name': 'Headlight Fluid',               'Price': 4             }           ]         }       ]     }");          string name = (string)o.SelectToken("Manufacturers[0].Name");     // Acme Co          decimal productPrice = (decimal)o.SelectToken("Manufacturers[0].Products[0].Price");     // 50          string productName = (string)o.SelectToken("Manufacturers[1].Products[0].Name");     // Elbow Grease ## SelectToken用JsonPath     JObject o = JObject.Parse(@"{       'Stores': [         'Lambton Quay',         'Willis Street'       ],       'Manufacturers': [         {           'Name': 'Acme Co',           'Products': [             {               'Name': 'Anvil',               'Price': 50             }           ]         },         {           'Name': 'Contoso',           'Products': [             {               'Name': 'Elbow Grease',               'Price': 99.95             },             {               'Name': 'Headlight Fluid',               'Price': 4             }           ]         }       ]     }");          // manufacturer with the name 'Acme Co'     JToken acme = o.SelectToken("$.Manufacturers[?(@.Name == 'Acme Co')]");          Console.WriteLine(acme);     // { "Name": "Acme Co", Products: [{ "Name": "Anvil", "Price": 50 }] }          // name of all products priced 50 and above     IEnumerable<JToken> pricyProducts = o.SelectTokens("$..Products[?(@.Price >= 50)].Name");          foreach (JToken item in pricyProducts)     {         Console.WriteLine(item);     }     // Anvil     // Elbow Grease ## SelectToken用LINQ     IList<string> storeNames = o.SelectToken("Stores").Select(s => (string)s).ToList();     // Lambton Quay     // Willis Street          IList<string> firstProductNames = o["Manufacturers"].Select(m => (string)m.SelectToken("Products[1].Name")).ToList();     // null     // Headlight Fluid          decimal totalPrice = o["Manufacturers"].Sum(m => (decimal)m.SelectToken("Products[0].Price"));     // 149.95 #XML轉JSON ## SerializeXmlNode     string xml = @"<?xml version='1.0' standalone='no'?>     <root>       <person id='1'>         <name>Alan</name>         <url>http://www.google.com</url>       </person>       <person id='2'>         <name>Louis</name>         <url>http://www.yahoo.com</url>       </person>     </root>";          XmlDocument doc = new XmlDocument();     doc.LoadXml(xml);          string jsonText = JsonConvert.SerializeXmlNode(doc);     //{     //  "?xml": {     //    "@version": "1.0",     //    "@standalone": "no"     //  },     //  "root": {     //    "person": [     //      {     //        "@id": "1",     //        "name": "Alan",     //        "url": "http://www.google.com"     //      },     //      {     //        "@id": "2",     //        "name": "Louis",     //        "url": "http://www.yahoo.com"     //      }     //    ]     //  }     //} ## XML屬性強制轉換爲Json     string xml = @"<person id='1'>       <name>Alan</name>       <url>http://www.google.com</url>       <role>Admin1</role>     </person>";          XmlDocument doc = new XmlDocument();     doc.LoadXml(xml);          string json = JsonConvert.SerializeXmlNode(doc);     //{     //  "person": {     //    "@id": "1",     //    "name": "Alan",     //    "url": "http://www.google.com",     //    "role": "Admin1"     //  }     //}          xml = @"<person xmlns:json='http://james.newtonking.com/projects/json' id='1'>       <name>Alan</name>       <url>http://www.google.com</url>       <role json:Array='true'>Admin</role>     </person>";          doc = new XmlDocument();     doc.LoadXml(xml);          json = JsonConvert.SerializeXmlNode(doc);     //{     //  "person": {     //    "@id": "1",     //    "name": "Alan",     //    "url": "http://www.google.com",     //    "role": [     //      "Admin"     //    ]     //  }     //} ## JSON轉換XML     string json = @"{       '?xml': {         '@version': '1.0',         '@standalone': 'no'       },       'root': {         'person': [           {             '@id': '1',             'name': 'Alan',             'url': 'http://www.google.com'           },           {             '@id': '2',             'name': 'Louis',             'url': 'http://www.yahoo.com'           }         ]       }     }";          XmlDocument doc = (XmlDocument)JsonConvert.DeserializeXmlNode(json);     // <?xml version="1.0" standalone="no"?>     // <root>     //   <person id="1">     //     <name>Alan</name>     //     <url>http://www.google.com</url>     //   </person>     //   <person id="2">     //     <name>Louis</name>     //     <url>http://www.yahoo.com</url>     //   </person>     // </root>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章