首頁  >  文章  >  後端開發  >  C# 建立 JSON 對象

C# 建立 JSON 對象

WBOY
WBOY原創
2024-09-03 15:31:12613瀏覽

在討論如何在 C# 中建立 JSON 物件之前,讓我們先了解一下 JSON 是什麼。 JSON 代表 JavaScript 物件表示法。它是一種非常輕量級的文字格式,用於交換資料。 JSON可以用三種樣式表示,即物件、陣列和字串。在這裡,我們將討論 JSON 物件。 JSON 物件以「{」開頭,以「}」結尾。 JSON 物件中的資料以鍵值對的形式存儲,鍵和值之間用冒號“:”分隔,每個鍵值對之間以逗號“,”分隔。

文法:

使用 Newtonsoft 套件建立 JSON 的語法如下:

ClassName objectName = new ClassName();
string jsonStr = JsonConvert.SerializeObject(objectName);

說明: 在上面的語法中,首先我們創建了需要JSON 格式資料的類別的對象,然後使用Newtonsoft 套件的JsonConvert.Serialize() 方法並將我們的類別對象傳遞為該方法的一個參數,該方法將物件的資料轉換為JSON 字串後傳回JSON 字串。

之後,我們可以使用以下語句將此 JSON 資料儲存到檔案中:

using(var streamWriter = new StreamWriter(filePath, true))
{
streamWriter.WriteLine(jsonStr.ToString());
streamWriter.Close();
}

在上面的語句中,我們建立了一個 StreamWriter 對象,用於將 JSON 資料寫入位置「filePath」指定的檔案中。然後,借助該對象,我們使用 WriteLine() 方法將 JSON 資料寫入檔案。

如何在 C# 中建立 JSON 物件?

在 C# 中,我們可以透過多種方式建立 JSON 對象,即使用 .NET 本機程式庫或使用第三方套件。

如果我們想使用原生.NET 程式庫來建立JSON 對象,那麼我們需要新增System. ServiceModel.Web 作為我們專案的引用,之後我們將能夠在程式碼中匯入System.Runtime.Serialization.Json 命名空間,其中包含一個名為DataContractJsonSerializer 的類,該類別負責將物件序列化為JSON 資料並反序列化JSON 資料到物件。

除此之外,我們還可以使用第三方套件來處理 JSON。就像 Newtonsoft.Json 套件一樣。要安裝此套件並將其新增至我們的專案中,我們需要在 Visual Studio 中執行以下步驟:

  • 前往「工具」> NuGet 套件管理器 >管理解決方案的 NuGet 套件。

C# 建立 JSON 對象

  • 在「瀏覽」標籤下搜尋「Newtonsoft.Json」套件並從顯示的結果中選擇它,然後選擇要新增此套件的項目。
  • 點選安裝按鈕。

C# 建立 JSON 對象

按照這些步驟操作後,當我們檢查項目的引用時,我們將新增「Newtonsoft.Json」。

我們現在可以在程式碼中匯入 Newtonsoft.Json 命名空間,其中包含一個名為 JsonConvert 的類,它提供了 .NET 類型和 JSON 類型之間的轉換方法。

C# 建立 JSON 物件的範例

顯示使用 .NET 本機庫建立 JSON 物件的範例。

範例#1

代碼:

using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Runtime.Serialization.Json;
using System.Runtime.Serialization;
namespace ConsoleApp4
{
[DataContractAttribute]
public class Student
{
[DataMemberAttribute]
public int RollNo { get; set; }
[DataMemberAttribute]
public string FirstName { get; set; }
[DataMemberAttribute]
public string LastName { get; set; }
[DataMemberAttribute]
public string Address { get; set; }
[DataMemberAttribute]
public float TotalMarks { get; set; }
public Student(int RollNo, string FirstName, string LastName,
string Address, float TotalMarks)
{
this.RollNo = RollNo;
this.FirstName = FirstName;
this.LastName = LastName;
this.Address = Address;
this.TotalMarks = TotalMarks;
}
}
public class Program
{
public static void Main(string[] args)
{
string jsonStr;
Student student = new Student(1, "Gaurang", "Pandya", "Thane, Mumbai", 800);
try
{
MemoryStream memoryStream = new MemoryStream();
//serializing object to JSON
DataContractJsonSerializer ser =
new DataContractJsonSerializer(student.GetType());
//writing JSON
ser.WriteObject(memoryStream, student);
memoryStream.Position = 0;
StreamReader streamReader = new StreamReader(memoryStream);
jsonStr = streamReader.ReadToEnd();
Console.WriteLine(jsonStr);
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
}
}

輸出:

C# 建立 JSON 對象

範例#2

範例顯示使用 .NET 本機程式庫建立 JSON 對象,然後使用 StreamWriter 將產生的 JSON 資料寫入檔案。

代碼:

using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Runtime.Serialization.Json;
using System.Runtime.Serialization;
namespace ConsoleApp4
{
[DataContractAttribute]
public class Student
{
[DataMemberAttribute]
public int RollNo;
[DataMemberAttribute]
public string FirstName;
[DataMemberAttribute]
public string LastName;
[DataMemberAttribute]
public string Address;
[DataMemberAttribute]
public float TotalMarks;
public Student(int RollNo, string FirstName, string LastName,
string Address, float TotalMarks)
{
this.RollNo = RollNo;
this.FirstName = FirstName;
this.LastName = LastName;
this.Address = Address;
this.TotalMarks = TotalMarks;
}
}
public class Program
{
public static void Main(string[] args)
{
string jsonStr;
string filePath = @"E:\Content\student.json";
Student student = new Student(1, "Gaurang", "Pandya", "Thane, Mumbai", 800);
try
{
MemoryStream memoryStream = new MemoryStream();
//serializing object to JSON
DataContractJsonSerializer ser =
new DataContractJsonSerializer(student.GetType());
//writing JSON
ser.WriteObject(memoryStream, student);
memoryStream.Position = 0;
StreamReader streamReader = new StreamReader(memoryStream);
jsonStr = streamReader.ReadToEnd();
//checking if the file already exists
if (File.Exists(filePath))
{
//deleting file if it exists
File.Delete(filePath);
}
//creating StreamWriter to write JSON data to file
using (StreamWriter streamWriter = new StreamWriter(filePath, true))
{
streamWriter.WriteLine(jsonStr.ToString());
streamWriter.Close();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
}
}

請在記事本中開啟的student.json 檔案中找到上述程式輸出的螢幕截圖。

輸出:

C# 建立 JSON 對象

範例 #3

顯示使用 Newtonsoft 套件建立 JSON 物件的範例。

代碼:

using System;
using Newtonsoft.Json;
namespace ConsoleApp4
{
public class Student
{
public int RollNo;
public string FirstName;
public string LastName;
public string Address;
public float TotalMarks;
public Student(int RollNo, string FirstName, string LastName,
string Address, float TotalMarks)
{
this.RollNo = RollNo;
this.FirstName = FirstName;
this.LastName = LastName;
this.Address = Address;
this.TotalMarks = TotalMarks;
}
}
public class Program
{
public static void Main(string[] args)
{
string jsonStr;
Student student = new Student(1, "Gaurang", "Pandya", "Thane, Mumbai", 800);
try
{
//serializing student object to JSON string
jsonStr = JsonConvert.SerializeObject(student);
Console.WriteLine(jsonStr);
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
}
}

輸出:

C# 建立 JSON 對象

結論

JSON 物件括在大括號內並包含鍵值對。鍵及其值由冒號分隔,其中鍵必須是字串,值可以是任何有效的資料類型。 JSON 物件中的每個鍵值對都以逗號分隔。

以上是C# 建立 JSON 對象的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
上一篇:C# 元組下一篇:C# 元組