Parsing JSON JSON.NET, LINQ-to-JSON

Slides:



Advertisements
Similar presentations
Processing JSON in.NET JSON, JSON.NET LINQ-to-JSON and JSON to XML SoftUni Team Technical Trainers Software University
Advertisements

Telerik Software Academy Databases.
Sets, Dictionaries SoftUni Team Technical Trainers Software University
XML Processing SoftUni Team Database Applications Technical Trainers
Exporting and Importing Data
Helpers, Data Validation
Auto Mapping Objects SoftUni Team Database Applications
Working with Fluent API Inheritance Strategies
Functional Programming
Introduction to Entity framework
Sets, Hash table, Dictionaries
C# Basic Syntax, Visual Studio, Console Input / Output
C# Basic Syntax, Visual Studio, Console Input / Output
Web API - Introduction AJAX, Spring Data REST SoftUni Team Web API
Introduction to MVC SoftUni Team Introduction to MVC
Deploying Web Application
PHP MVC Frameworks Course Introduction SoftUni Team Technical Trainers
PHP Fundamentals Course Introduction SoftUni Team Technical Trainers
C# Database Fundamentals with Microsoft SQL Server
Introduction to Entity Framework
Application Architecture, Redux
ASP.NET Integration Testing
Classes, Properties, Constructors, Objects, Namespaces
Mocking tools for easier unit testing
State Management Cookies, Sessions SoftUni Team State Management
EF Code First (Advanced)
PHP MVC Frameworks MVC Fundamentals SoftUni Team Technical Trainers
C# Databases Advanced with Microsoft SQL Server
EF Advanced Querying Optimize Performance SoftUni Team Advanced
EF Relations Object Composition
Entity Framework: Code First
Parsing XML XDocument and LINQ
Entity Framework DB From Code, OOP Introduction
Data Definition and Data Types
Install and configure theme
Entity Framework: Relations
Caching Data in ASP.NET MVC
Fast String Manipulation
Functional Programming
ASP.NET Razor Engine SoftUni Team ASP.NET MVC Introduction
MVC Architecture, Symfony Framework for PHP Web Apps
Transactions in Entity Framework
Exporting and Importing Data
Databases Advanced Course Introduction SoftUni Team Databases Advanced
Best Practices and Architecture
Best practices and architecture
Arrays and Multidimensional Arrays
Magento Basics part 2 Modules & Themes Stenik Group Ltd. Magento
Data Definition and Data Types
Multidimensional Arrays, Sets, Dictionaries
Extending functionality using Collections
ASP.NET REST Services SoftUni Team ASP.NET REST Services
Exporting and Importing Data
Making big SPA applications
Manual Mapping and AutoMapper Library
Functional Programming
ASP.NET Razor Engine SoftUni Team ASP.NET MVC Introduction
Exporting and Importing Data
Scheduled Tasks and Web Socket
Introduction to TypeScript & Angular
CSS Transitions and Animations
Train the Trainers Course
Spring Data Advanced Querying
JavaScript Frameworks & AngularJS
Text Processing and Regex API
/^Hel{2}o\s*World\n$/
Lean .NET stack for building modern web apps
JavaScript: ExpressJS Overview
CSS Transitions and Animations
Iterators and Generators
Presentation transcript:

Parsing JSON JSON.NET, LINQ-to-JSON JSON Processing Parsing JSON JSON.NET, LINQ-to-JSON JSON SoftUni Team Technical Trainers Software University http://softuni.bg © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

Table of Contents JSON Data Format Processing JSON JSON.NET © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

sli.do #Entity Questions © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

The JSON Data Format Definition and Syntax

JSON Data Format JSON (JavaScript Object Notation) is a lightweight data format Human and machine-readable plain text Based on objects in JavaScript Independent of development platforms and languages JSON data consists of: Values (strings, numbers, etc.) Key-value pairs: { key : value } Arrays: [value1, value2, …}

JSON Data Format (2) The JSON data format follows the rules of object creation in JS Strings, numbers and Booleans are valid JSON: Arrays are valid JSON: Objects are valid JSON (key-value pairs): "this is string and is valid JSON" 3.14 true [5, "text", true] { "firstName": "Vladimir", "lastName": "Georgiev", "jobTitle": "Technical Trainer", "age": 25 }

Parsing JSON in C# and .NET Processing JSON Parsing JSON in C# and .NET

Built-in JSON Serializers .NET has a built-in JavaScriptSerializer class Contained in System.Web.Extensions assembly Load assembly reference from the project’s context menu

Built-in JSON Serializers (2) JavaScriptSerializer can parse from object to JSON string and vice versa: var product = new Product(…); var serializer = new JavaScriptSerializer(); var jsonProduct = serializer.Serialize(product); var objProduct = serializer.Deserialize<Product>(jsonProduct); Specify type { "Id":0, "Name":"Oil Pump", "Description":null, "Cost":25 }

Parsing Dictionaries JavaScriptSerializer can correctly parse dictionaries var products = new Dictionary<string, Product> { { "pump", firstProduct }, { "filter", secondProduct } }; var jsonProducts = serializer.Serialize(products); var objProducts = serializer.Deserialize<Dictionary<string, Product>>(jsonProducts); { "pump":{"Id":0,"Name":"Oil Pump","Description":null,"Cost":25}, "filter":{"Id":0,"Name":"Oil Filter","Description":null,"Cost":15} }

Better JSON Parsing for .NET Developers Newtonsoft Json.NET JSON.NET Better JSON Parsing for .NET Developers

What is JSON.NET? JSON.NET is a framework for .NET Better performance than JavaScriptSerializer Supports LINQ-to-JSON Out-of-the-box support for parsing between JSON and XML Open-source project: http://www.newtonsoft.com

Installing JSON.NET To install JSON.NET use the NuGet Package Manager: Or with a command in the Package Manager Console: Install-Package Newtonsoft.Json

General Usage JSON.NET exposes a static service JsonConvert Used for parsing and configuration To Serialize an object: To Deserialize an object: var jsonProduct = JsonConvert.SerializeObject(product); var objProduct = JsonConvert.DeserializeObject<Product>(jsonProduct);

JSON.NET Features 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 parsing between XML and JSON

Configuring JSON.NET By default, the result is a single line of text To indent the output string use Formatting.Indented JsonConvert.SerializeObject(products, Formatting.Indented); { "pump": { "Id": 0, "Name": "Oil Pump", "Description": null, "Cost": 25.0 }, "filter": { "Name": "Oil Filter", "Cost": 15.0 }

Configuring JSON.NET Deserializing to anonymous types: Incoming JSON var json = @"{ 'firstName': 'Vladimir', 'lastName': 'Georgiev', 'jobTitle': 'Technical Trainer' }"; var template = new { FirstName = string.Empty, LastName = string.Empty, Occupation = string.Empty }; var person = JsonConvert.DeserializeAnonymousType(json, template); Template objects

JSON.NET Parsing of Objects 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")] public string Username { get; set; } [JsonIgnore] public string Password { get; set; } } Parse Username to user Skip the property

LINQ-to-JSON LINQ-to-JSON works with JObjects Create from JSON string: Read from file: Used like objects in JavaScript JObject obj = JObject.Parse(jsonProduct); using (StreamReader reader = File.OpenText(@"c:\categories.json")) { JObject o = (JObject)JToken.ReadFrom(new JsonTextReader(reader)); // … } Console.WriteLine(obj["Name"]); // Oil Pump

LINQ-to-JSON (2) JObjects can be queried with LINQ var json = @"{'products': [ {'name': 'Fruits', 'products': ['apple', 'banana', 'orange']}, {'name': 'Vegetables', 'products': ['cucumber', 'potato', 'eggplant']}]}"; int index = 1; List<string> products = json["products"].Select(c => string.Format("{0}. {1} ({2})", index++, c["name"], string.Join(", ", c["products"]) )) // 1. Fruits (apple, banana, orange) // 2. Vegetables (cucumber, potato, eggplant)

Summary JSON is a cross platform data format JavaScriptSerializer is the default processor of JSON in C# JSON.NET is a fast framework for working with JSON data © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

JSON Processing https://softuni.bg/courses/ © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

License This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International" license Attribution: this work may contain portions from "Databases" course by Telerik Academy under CC-BY-NC-SA license © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

Free Trainings @ Software University Software University Foundation – softuni.org Software University – High-Quality Education, Profession and Job for Software Developers softuni.bg Software University @ Facebook facebook.com/SoftwareUniversity Software University Forums forum.softuni.bg © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.