Download presentation
Presentation is loading. Please wait.
1
Telerik Software Academy http://academy.telerik.com Databases
2
The JSON data format Rules and features Usage JSON.NET Overview Installation and usage LINQ-to-JSON JSON to XML and XML to JSON
3
What is JSON?
4
JSON (JavaScript Object Notation) is a lightweight data format Human and machine-readable Based on the way of creating objects in JS Platform independent – can be used with any programming language
5
The JSON data format follows the rules of object creation in JavaScript Strings, numbers and Booleans are valid JSON "this is string and is valid JSON" Arrays are valid JSON [5, 'string', true] Objects are valid JSON { "firstname": "Doncho", "firstname": "Doncho", "lastname": "Minkov", "lastname": "Minkov", "occupation": "Technical trainer" "occupation": "Technical trainer"}
6
The JSON data format follows the rules of object creation in JavaScript Strings, numbers and Booleans are valid JSON "this is string and is valid JSON" Arrays are valid JSON [5, 'string', true] Objects are valid JSON { "firstname": "Doncho", "firstname": "Doncho", "lastname": "Minkov", "lastname": "Minkov", "occupation": "Technical trainer" "occupation": "Technical trainer"} The double quotes for the keys are mandatory
7
How to parse JSON in.NET?
8
.NET has built-in JSON serializer: The JavaScriptSerializer class, contained in System.Web.Extensions assembly JavaScriptSerializer is able to parse C# object to JSON string and vice versa: var place = new Place(…); var serializer = new JavaScriptSerializer(); var jsonPlace = serializer.Serialize(place); var objPlace = serializer.Deserialize (jsonPlace);
9
Live Demo
10
JavaScript serializer has nice features: Serializing objects to JSON and vice versa Correct parsing of dictionaries: digits = new Dictionary digits = new Dictionary { { "one", 1}, { "one", 1}, { "two", 2}, { "two", 2}, … }; };
11
JavaScript serializer has nice features: Serializing objects to JSON and vice versa Correct parsing of dictionaries: digits = new Dictionary digits = new Dictionary { { "one", 1}, { "one", 1}, { "two", 2}, { "two", 2}, … }; };{ "one": 1, "two": 2, "one": 1, "two": 2, "three": 3, "three": 3, "four": 4, "four": 4,…} Is parsed to
12
JavaScript serializer has nice features: Serializing objects to JSON and vice versa Correct parsing of dictionaries: digits = new Dictionary digits = new Dictionary { { "one", 1}, { "one", 1}, { "two", 2}, { "two", 2}, … }; };{ "one": 1, "two": 2, "one": 1, "two": 2, "three": 3, "three": 3, "four": 4, "four": 4,…} Is parsed to
13
Live Demo
14
Better JSON parsing than with JavaScriptSerializer
15
JavaScriptSerializer is good But JSON.NET is better JSON.NET: Has better performance Supports LINQ-to-JSON Has an out-of-the-box support for parsing between JSON and XML
16
To install JSON.NET, run in the Package Manager Console: $ Install-Package Newtonsoft.Json Has two primary methods: Serialize an object: var serializedPlace = JsonConvert.SerializeObject(place); JsonConvert.SerializeObject(place); var deserializedPlace = JsonConvert.DeserializeObject (serializedPlace); JsonConvert.DeserializeObject (serializedPlace); Deserialize an object:
17
Live Demo
18
JSON.NET can be configured to: Indent the output JSON string To convert JSON to anonymous types To control the casing and properties to parse To skip errors JSON.NET also supports: LINQ-to-JSON Direct parse between XML and JSON
19
var json = @"{ 'firstName': 'Doncho'," 'lastName': 'Minkov', 'occupation': 'Technical Trainer' }"; 'lastName': 'Minkov', 'occupation': 'Technical Trainer' }"; var template = new { FirstName = "", FirstName = "", Lastname = "", Lastname = "", Occupation = "" Occupation = ""}; var person = JsonConvert.DeserializeAnonymousType(json, template); JsonConvert.DeserializeAnonymousType(json, template); To indent the output string use Formattingg.Indented : JsonConvert.SerializeObject(place, Formatting.Indented); Deserializing to anonymous types:
20
var json = @"{ 'firstName': 'Doncho'," 'lastName': 'Minkov', 'occupation': 'Technical Trainer' }"; 'lastName': 'Minkov', 'occupation': 'Technical Trainer' }"; var template = new { FirstName = "", FirstName = "", Lastname = "", Lastname = "", Occupation = "" Occupation = ""}; var person = JsonConvert.DeserializeAnonymousType(json, template); JsonConvert.DeserializeAnonymousType(json, template); Should provide a template To indent the output string use Formattingg.Indented : JsonConvert.SerializeObject(place, Formatting.Indented); Deserializing to anonymous types:
21
Live Demo
22
By default JSON.NET takes each Property/Field from the public interface of a class and parses it This can be controlled using attributes: public class User { [JsonProperty("user")] [JsonProperty("user")] public string Username{get;set;} public string Username{get;set;} [JsonIgnore] [JsonIgnore] public string Password{get;set;} public string Password{get;set;}}
23
By default JSON.NET takes each Property/Field from the public interface of a class and parses it This can be controlled using attributes: public class User { [JsonProperty("user")] [JsonProperty("user")] public string Username{get;set;} public string Username{get;set;} [JsonIgnore] [JsonIgnore] public string Password{get;set;} public string Password{get;set;}} Tells the converter to parse "Username" to "user"
24
By default JSON.NET takes each Property/Field from the public interface of a class and parses it as is This can be controlled using attributes: public class User { [JsonProperty("user")] [JsonProperty("user")] public string Username{get;set;} public string Username{get;set;} [JsonIgnore] [JsonIgnore] public string Password{get;set;} public string Password{get;set;}} Tells the converter to skip the property "Password" Tells the converter to parse "Username" to "user"
25
Live Demo
26
JSON.NET has a support for LINQ-to-JSON var jsonObj = JObject.Parse(json); Console.WriteLine("Places in {0}:", jsonObj["name"]); jsonObj["places"].Select( pl => pl => string.Format("{0}) {1} ({2})", string.Format("{0}) {1} ({2})", index++, index++, pl["name"], pl["name"], string.Join(", ", string.Join(", ", pl["categories"].Select( pl["categories"].Select( cat => cat["name"])))) cat => cat["name"])))).Print();.Print();
27
Live Demo
29
Conversions from JSON to XML are done using two methods: XML to JSON string jsonFromXml = JsonConvert.SerializeXNode(doc); XDocument xmlFromJson = JsonConvert.DeserializeXNode(json); JSON to XML
30
Live Demo
31
форум програмиране, форум уеб дизайн курсове и уроци по програмиране, уеб дизайн – безплатно програмиране за деца – безплатни курсове и уроци безплатен SEO курс - оптимизация за търсачки уроци по уеб дизайн, HTML, CSS, JavaScript, Photoshop уроци по програмиране и уеб дизайн за ученици ASP.NET MVC курс – HTML, SQL, C#,.NET, ASP.NET MVC безплатен курс "Разработка на софтуер в cloud среда" BG Coder - онлайн състезателна система - online judge курсове и уроци по програмиране, книги – безплатно от Наков безплатен курс "Качествен програмен код" алго академия – състезателно програмиране, състезания ASP.NET курс - уеб програмиране, бази данни, C#,.NET, ASP.NET курсове и уроци по програмиране – Телерик академия курс мобилни приложения с iPhone, Android, WP7, PhoneGap free C# book, безплатна книга C#, книга Java, книга C# Николай Костов - блог за програмиране http://academy.telerik.com
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.