ホームページ  >  記事  >  バックエンド開発  >  C# JSON オブジェクトを作成する

C# JSON オブジェクトを作成する

WBOY
WBOYオリジナル
2024-09-03 15:31:12613ブラウズ

C# で JSON オブジェクトを作成する方法を説明する前に、まず JSON とは何かを理解しましょう。 JSON は JavaScript Object Notation の略です。データ交換に使用される非常に軽量なテキスト形式です。 JSON はオブジェクト、配列、文​​字列の 3 つのスタイルで表現できます。ここでは、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();
}

上記のステートメントでは、場所「filePath」で指定されたファイルに JSON データを書き込むための StreamWriter のオブジェクトを作成しました。次に、このオブジェクトを利用して、WriteLine() メソッドを使用して JSON データをファイルに書き込みました。

C# で JSON オブジェクトを作成するにはどうすればよいですか?

C# では、.NET ネイティブ ライブラリやサードパーティ パッケージを使用するなど、さまざまな方法で JSON オブジェクトを作成できます。

ネイティブ .NET ライブラリを使用して JSON オブジェクトを作成したい場合は、System.NET を追加する必要があります。 ServiceModel.Web をプロジェクトへの参照としてこの後、オブジェクトを JSON データにシリアル化し、JSON データを逆シリアル化する DataContractJsonSerializer というクラスを含むコード内に System.Runtime.Serialization.Json 名前空間をインポートできるようになります。オブジェクトに。

これとは別に、サードパーティのパッケージを使用して JSON を操作できます。 Newtonsoft.Json パッケージと同様です。このパッケージをインストールしてプロジェクトに追加するには、Visual Studio で以下の手順に従う必要があります:

  • [ツール] > [ツール] に移動します。 NuGet パッケージ マネージャー >ソリューションの NuGet パッケージを管理します。

C# JSON オブジェクトを作成する

  • 「参照」タブで「Newtonsoft.Json」パッケージを検索し、表示された結果からそれを選択し、このパッケージを追加するプロジェクトを選択します。
  • インストールボタンをクリックします。

C# JSON オブジェクトを作成する

これらの手順に従ってプロジェクトの参照を確認すると、「Newtonsoft.Json」が追加されます。

これで、.NET 型と JSON 型の間の変換メソッドを提供する JsonConvert というクラスを含むコードに Newtonsoft.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 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
前の記事:C# タプル次の記事:C# タプル