External Format Processing
Parsing JSON, JSON.NET
SoftUni Team
Technical Trainers
Software University
http://softuni.bg
Table of Contents
1. JSON Data Format
2. Processing JSON
3. JSON.NET
2
Have a Question?
sli.do
#CSharpDB
3
{JSON}
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 JavaScript objects
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:
"this is a string and is valid JSON" 3.14 true
Arrays are valid JSON:
[5, "text", true]
Objects are valid JSON (key-value pairs):
{
"firstName": "Vladimir", "lastName": "Georgiev",
"jobTitle": "Technical Trainer", "age": 25
}
JSON Object
An object is an unordered set of name/value pairs. An object
begins with { (left brace) and ends with } (right brace). Each
name is followed by : (colon) and the name/value pairs are
separated by , (comma)
JSON Array
An array is an ordered collection of values. An array begins with
[ (left bracket) and ends with ] (right bracket). Values are
separated by , (comma)
JSON Value
A value can be a string in double quotes, or a number, or true
or false or null, or an object or an array. These structures can
be nested
JSON String
A string is a sequence of
zero or more Unicode
characters, wrapped in
double quotes, using
backslash escapes. A
character is represented
as a single character
string
JSON Number
A number is very much like a C or Java number, except that the
octal and hexadecimal formats are not used
{JSON}
Processing JSON
Parsing JSON in C# and .NET
Built-in JSON Support
.NET has a built-in DataContractJsonSerializer class
Contained in System.Runtime.Serialization
assembly
Supports deserializing (parsing) strings and
serializing objects
Including DataContractJsonSerializer into a project:
using System.Runtime.Serialization.Json;
Serializing JSON
DataContractJsonSerializer can serialize an object:
static string SerializeJson<T>(T obj)
{
var serializer = new DataContractJsonSerializer(obj.GetType());
using (var stream = new MemoryStream())
{
serializer.WriteObject(stream, obj);
var result = Encoding.UTF8.GetString(stream.ToArray());
return result;
}
}
{
"Id":0,
"Name":"Oil Pump",
"Description":null,
"Cost":25
}
Deserializing JSON
DataContractJsonSerializer can deserialize a JSON string:
static T DeserializeJson<T>(string jsonString)
{
var serializer = new DataContractJsonSerializer(typeof(T));
var jsonStringBytes = Encoding.UTF8.GetBytes(jsonString);
using (var stream = new MemoryStream(jsonStringBytes))
{
var result = (T)serializer.ReadObject(stream);
return result;
}
}
{
"Id":0,
"Name":"Oil Pump",
"Description":null,
"Cost":25
}
Newtonsoft
Json.NET
JSON.NET
Better JSON Parsing for .NET Developers
What is JSON.NET?
JSON.NET is a JSON framework for .NET
More functionality than built-in functionality
Supports LINQ-to-JSON
Out-of-the-box support for parsing between JSON and XML
Open-source project: http://www.newtonsoft.com
Json.NET vs .NET Serializers: https://www.newtonsoft.com/jso
n/help/html/JsonNetVsDotNetSerializers.htm
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:
var jsonProduct = JsonConvert.SerializeObject(product);
To Deserialize an object:
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": {
"Id": 0,
"Name": "Oil Filter",
"Description": null,
"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, Template
Occupation = string.Empty
};
objects
var person = JsonConvert.DeserializeAnonymousType(json, template);
JSON.NET Parsing of Objects
By default JSON.NET takes each property / field from the class
and parses it
This can be controlled using attributes:
public class User Parse Username
{ to user
[JsonProperty("user")]
public string Username { get; set; }
[JsonIgnore] Skip the property
public string Password { get; set; }
}
JSON.NET Parsing of Objects
By default JSON.NET takes each property / field from the class
and parses it
This can be controlled using ContractResolver:
DefaultContractResolver contractResolver = new DefaultContractResolver()
{
NamingStrategy = new SnakeCaseNamingStrategy()
};
var serialized = JsonConvert.SerializeObject(person, new JsonSerializerSettings()
{
ContractResolver = contractResolver,
Formatting = Formatting.Indented
});
LINQ-to-JSON
LINQ-to-JSON works with JObjects
Create from JSON string:
JObject obj = JObject.Parse(jsonProduct);
Reading from file:
var people = JObject.Parse(File.ReadAllText(@"c:\people.json"))
Using JObject:
foreach (JToken person in people)
{
Console.WriteLine(person["FirstName"]); // Ivan
Console.WriteLine(person["LastName"]); // Petrov
}
25
LINQ-to-JSON (2)
JObjects can be queried with LINQ
var json = JObject.Parse(@"{'products': [
{'name': 'Fruits', 'products': ['apple', 'banana']},
{'name': 'Vegetables', 'products': ['cucumber']}]}");
var products = json["products"].Select(t =>
string.Format("{0} ({1})",
t["name"],
string.Join(", ", c["products"])
))
// Fruits (apple, banana)
// Vegetables (cucumber)
XML-to-JSON
Json.NET supports converting JSON to XML and vice versa
using the XmlNodeConverter
Conversion Rules
Elements remain unchanged.
Attributes are prefixed with an @ and should be at the start of the object.
Single child text nodes are a value directly against an element, otherwise they are accessed
via #text.
The XML declaration and processing instructions are prefixed with ?.
Character data, comments, whitespace and significant whitespace nodes are accessed via
#cdata-section, #comment, #whitespace and #significant-whitespace respectively
Multiple nodes with the same name at the same level are grouped together into an array.
Empty elements are null.
XML-to-JSON
{
"?xml": {
"@version": "1.0",
string xml = @"<?xml version='1.0' standalone='no'?>
"@standalone": "no"
<root>
},
<person id='1'>
"root": {
<name>Alan</name>
"person": [
<url>www.google.com</url>
{
</person>
"@id": "1",
<person id='2'>
"name": "Alan",
<name>Louis</name>
"url": "www.google.com"
<url>www.yahoo.com</url>
},
</person>
{
</root>";
"@id": "2",
"name": "Louis",
XmlDocument doc = new XmlDocument();
"url": "www.yahoo.com"
doc.LoadXml(xml);
}
string jsonText = JsonConvert.SerializeXmlNode(doc);
]
}
}
Summary
JSON
… is cross platform data
format
…
DataContractJsonSerializer
… is the
default JSON Parser in C#
JSON.NET is a fast framework for
working with JSON data
29
https://softuni.bg/courses/databases-advanced-entity-framework
SoftUni Diamond Partners
SoftUni Organizational Partners
Trainings @ Software University (SoftUni)
Software University – High-Quality Education and
Employment Opportunities
softuni.bg
Software University Foundation
http://softuni.foundation/
Software University @ Facebook
facebook.com/SoftwareUniversity
Software University Forums
forum.softuni.bg
License
This course (slides, examples, demos, videos, homework, etc.)
is licensed under the "Creative Commons Attribution-NonCom
mercial-ShareAlike 4.0 International" license
34