Working with JSON - potatoscript/csharp GitHub Wiki

πŸ“š Working with JSON in C# πŸ“š


πŸ₯” What is JSON?

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.


πŸ“„ Example of JSON:

{
  "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 or false
    • Arrays – Lists of values like ["French Fries", "Mashed Potatoes"]
    • Objects – Another JSON inside, like a mini recipe!

🎯 Why Use JSON in C#?

βœ… Easy to work with – Simple to parse and generate.
βœ… Flexible – Can handle various types of data.
βœ… Interoperable – Used in web APIs, configurations, and more.


πŸ“ Setting Up JSON Handling in C#

To work with JSON in C#, we use the powerful Newtonsoft.Json library, also known as Json.NET. 🍟✨


πŸ“¦ Step 1: Install Newtonsoft.Json Package

  1. Open your project in Visual Studio.
  2. Open the NuGet Package Manager:
    • Right-click on your project in Solution Explorer.
    • Select Manage NuGet Packages....
  3. Search for Newtonsoft.Json.
  4. Click Install.

Or install it using the NuGet Package Manager Console:

Install-Package Newtonsoft.Json

πŸ“ Basic JSON Operations in C#

🎯 Step 2: Import Newtonsoft.Json

using System;
using System.Collections.Generic;
using Newtonsoft.Json;

πŸ“ Step 3: Serialize (Convert) an Object to JSON

Serialization means converting a C# object into a JSON string.


🧠 Example:

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; }
}

🎁 Output:

πŸ₯” 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.

πŸ“ Step 4: Deserialize (Convert) JSON to an Object

Deserialization means converting a JSON string back into a C# object.


🧠 Example:

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; }
}

🎁 Output:

πŸ₯” 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.

πŸ“ Step 5: Working with JSON Arrays

If the JSON contains an array, we can convert it into a List in C#.


🧠 Example:

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; }
}

🎁 Output:

πŸ₯” 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.

πŸ“ Step 6: Writing JSON to a File

You can save the JSON string into a file using File.WriteAllText().


🧠 Example:

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; }
}

🎁 Output:

πŸ“„ JSON data saved to potato.json!

πŸ“ Step 7: Reading JSON from a File

To read JSON data from a file, use File.ReadAllText().


🧠 Example:

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; }
}

🎁 Output:

πŸ₯” Name: Sweet Potato, Type: Japanese Yam, Price: 4.0 per kg, Organic: True
⚠️ **GitHub.com Fallback** ⚠️