[C#] Using JSON.NET(Newtonsoft) method for JSON

  • 125
  • 0
  • 2024-02-22

How to write/read data for json format

Step 1. 確認你的JSON字串

想要好好組合你的JSON語言, 可以使用這個工具 JSON Editor Online

Sample :

{
  "greeting": "Welcome to quicktype!",
  "instructions": [
    "Type or paste JSON here",
    "Or choose a sample above"
  ],
  "sample": {
    "step1": "111",
    "step2": 222
  }
}

Step 2. 使用你的JSON資料 [ 使用物件作法(強型別) ]

  • 說明 : 需要預設JSON格式的物件, 附上輔助工具 json2csharp
  • JSON.NET : 處理JSON資料的好工具, 可以在Visual Studio NuGet上找到, 官網, 說明

處理結果如下所示 :

using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

public class Welcome
{
    public string Greeting { get; set; }
    public List<string> Instructions { get; set; }
    public SampleObj Sample { get; set; }
}

public class SampleObj
{
    public string Step1 { get; set; }
    public int Step2 { get; set; }
}

執行反序列化, 將 JSON 字串轉換為自訂義物件

string sJson = @"{""greeting"":""Welcome to quicktype!"",""instructions"":[""Type or paste JSON here"",""Or choose a sample above""],""sample"":{""step1"":""111"",""step2"":222}}";
Welcome MyObject = JsonConvert.DeserializeObject<Welcome>(sJson);

另外一種執行反序列化方法

var vWelcome = JsonConvert.Deserialize<dynamic>(sJson);
string sGreeting = vWelcome.Greeting;

接著執行序列化, 將自訂義物件轉換為 JSON 字串

sJson = JsonConvert.SerializeObject(MyObject);

以上就是簡易的JSON處理方法