Working with JSON - potatoscript/csharp GitHub Wiki
JSON (JavaScript Object Notation) is a lightweight format used to store and transfer data. Itβs super easy to read and write, and itβs widely used for exchanging information between a client and a server.
π Think of JSON like a potato recipe π₯π² β the ingredients and instructions (data) are organized in a neat, structured way, so you can easily understand and follow the steps.
{
"name": "PotatoScript",
"age": 10,
"favorite_foods": ["French Fries", "Mashed Potatoes", "Potato Chips"],
"is_coder": true
}
β Explanation:
-
{}
β Curly braces group everything together. - "name" β This is a key.
- "PotatoScript" β This is the value.
- JSON consists of key-value pairs where the keys are strings and the values can be:
-
Strings β
"PotatoScript"
-
Numbers β
10
-
Boolean β
true
orfalse
-
Arrays β Lists of values like
["French Fries", "Mashed Potatoes"]
- Objects β Another JSON inside, like a mini recipe!
-
Strings β
β
Easy to work with β Simple to parse and generate.
β
Flexible β Can handle various types of data.
β
Interoperable β Used in web APIs, configurations, and more.
To work with JSON in C#, we use the powerful Newtonsoft.Json library, also known as Json.NET. πβ¨
- Open your project in Visual Studio.
- Open the NuGet Package Manager:
- Right-click on your project in Solution Explorer.
- Select Manage NuGet Packages....
- Search for
Newtonsoft.Json
. - Click Install.
Or install it using the NuGet Package Manager Console:
Install-Package Newtonsoft.Json
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
Serialization means converting a C# object into a JSON string.
using System;
using Newtonsoft.Json;
class Program
{
static void Main()
{
// Create a potato object π₯
Potato potato = new Potato
{
Name = "Golden Potato",
Type = "Yukon Gold",
PricePerKg = 3.5,
IsOrganic = true
};
// Convert object to JSON string
string jsonData = JsonConvert.SerializeObject(potato, Formatting.Indented);
// Display the JSON data
Console.WriteLine("π₯ Potato JSON Data:");
Console.WriteLine(jsonData);
}
}
// Define Potato class
class Potato
{
public string Name { get; set; }
public string Type { get; set; }
public double PricePerKg { get; set; }
public bool IsOrganic { get; set; }
}
π₯ Potato JSON Data:
{
"Name": "Golden Potato",
"Type": "Yukon Gold",
"PricePerKg": 3.5,
"IsOrganic": true
}
β Explanation:
-
JsonConvert.SerializeObject()
converts the C# object to a JSON string. -
Formatting.Indented
makes the JSON easier to read by adding indentation.
Deserialization means converting a JSON string back into a C# object.
using System;
using Newtonsoft.Json;
class Program
{
static void Main()
{
// JSON string representing a potato π₯
string jsonData = @"{
""Name"": ""Golden Potato"",
""Type"": ""Yukon Gold"",
""PricePerKg"": 3.5,
""IsOrganic"": true
}";
// Convert JSON to Potato object
Potato potato = JsonConvert.DeserializeObject<Potato>(jsonData);
// Display potato information
Console.WriteLine($"π₯ Name: {potato.Name}");
Console.WriteLine($"π₯ Type: {potato.Type}");
Console.WriteLine($"π° Price: {potato.PricePerKg} per kg");
Console.WriteLine($"π± Organic: {potato.IsOrganic}");
}
}
// Define Potato class
class Potato
{
public string Name { get; set; }
public string Type { get; set; }
public double PricePerKg { get; set; }
public bool IsOrganic { get; set; }
}
π₯ Name: Golden Potato
π₯ Type: Yukon Gold
π° Price: 3.5 per kg
π± Organic: True
β Explanation:
-
JsonConvert.DeserializeObject<T>()
converts the JSON string to a C# object. - The properties of the JSON map directly to the properties in the Potato class.
If the JSON contains an array, we can convert it into a List in C#.
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
class Program
{
static void Main()
{
// JSON array representing a list of potatoes π₯
string jsonData = @"[
{ ""Name"": ""Golden Potato"", ""Type"": ""Yukon Gold"", ""PricePerKg"": 3.5, ""IsOrganic"": true },
{ ""Name"": ""Red Potato"", ""Type"": ""Red Bliss"", ""PricePerKg"": 3.0, ""IsOrganic"": false },
{ ""Name"": ""Russet Potato"", ""Type"": ""Russet"", ""PricePerKg"": 2.8, ""IsOrganic"": true }
]";
// Convert JSON array to List<Potato>
List<Potato> potatoes = JsonConvert.DeserializeObject<List<Potato>>(jsonData);
// Display potato information
foreach (var potato in potatoes)
{
Console.WriteLine($"π₯ Name: {potato.Name}, Type: {potato.Type}, Price: {potato.PricePerKg} per kg, Organic: {potato.IsOrganic}");
}
}
}
// Define Potato class
class Potato
{
public string Name { get; set; }
public string Type { get; set; }
public double PricePerKg { get; set; }
public bool IsOrganic { get; set; }
}
π₯ Name: Golden Potato, Type: Yukon Gold, Price: 3.5 per kg, Organic: True
π₯ Name: Red Potato, Type: Red Bliss, Price: 3.0 per kg, Organic: False
π₯ Name: Russet Potato, Type: Russet, Price: 2.8 per kg, Organic: True
β Explanation:
- JSON arrays are deserialized into a List.
- We loop through the list and display the information.
You can save the JSON string into a file using File.WriteAllText()
.
using System;
using System.IO;
using Newtonsoft.Json;
class Program
{
static void Main()
{
Potato potato = new Potato
{
Name = "Sweet Potato",
Type = "Japanese Yam",
PricePerKg = 4.0,
IsOrganic = true
};
// Convert object to JSON
string jsonData = JsonConvert.SerializeObject(potato, Formatting.Indented);
// Write JSON to a file
File.WriteAllText("potato.json", jsonData);
Console.WriteLine("π JSON data saved to potato.json!");
}
}
// Define Potato class
class Potato
{
public string Name { get; set; }
public string Type { get; set; }
public double PricePerKg { get; set; }
public bool IsOrganic { get; set; }
}
π JSON data saved to potato.json!
To read JSON data from a file, use File.ReadAllText()
.
using System;
using System.IO;
using Newtonsoft.Json;
class Program
{
static void Main()
{
// Read JSON data from file
string jsonData = File.ReadAllText("potato.json");
// Deserialize JSON to object
Potato potato = JsonConvert.DeserializeObject<Potato>(jsonData);
// Display potato info
Console.WriteLine($"π₯ Name: {potato.Name}, Type: {potato.Type}, Price: {potato.PricePerKg} per kg, Organic: {potato.IsOrganic}");
}
}
// Define Potato class
class Potato
{
public string Name { get; set; }
public string Type { get; set; }
public double PricePerKg { get; set; }
public bool IsOrganic { get; set; }
}
π₯ Name: Sweet Potato, Type: Japanese Yam, Price: 4.0 per kg, Organic: True