《json2csharp》C# 解析 JSON 好工具,快速產生解 JSON 程式碼

在 C# 的開發上,難免有遇到 JSON 需要解析的地方,而 json2csharp (記法: Json to c# ) 是一個解析 JSON 的工具,透過這個線上工具,就可以馬上把 JSON 變成程式碼,也可以將 json array Parser 成  list class,讓你在 C# 程式中快速使用,如果你有在 C# 中解析 JSON 的需求, json2csharp 是你不可以錯過的好工具。

 

json2csharp

 

◎◎網站小檔案◎◎
網站名稱:json2csharp
網站介面:英文
網站性質:免費
是否需要登入:不需要
■ 網站網址:http://json2csharp.com/

 

如圖,在下方空白處輸入 JSON 的字串,輸入後按下【Generate】。

json2csharp 1

 

接下來,網頁就幫你解析完啦!就把這段程式碼複製到程式中囉!是不是很容易呢?

json2csharp 2

 

原始的 JSON 字串如下:

{
  'events': [
    {
      'type': 'message',
      'replyToken': '6dd4ed3fc9e6425eb5f62abf32aa5171',
      'source': {
        'userId': '123',
        'type': 'user'
      },
      'timestamp': 1499395564366,
      'message': {
        'type': 'text',
        'id': '6349945974895',
        'text': 'Hi'
      }
    }
  ]
}

 

 

而這段程式碼如下:

   public class Source
{
    public string userId { get; set; }
    public string type { get; set; }
}

public class Message
{
    public string type { get; set; }
    public string id { get; set; }
    public string text { get; set; }
}

public class Event
{
    public string type { get; set; }
    public string replyToken { get; set; }
    public Source source { get; set; }
    public long timestamp { get; set; }
    public Message message { get; set; }
}

public class RootObject
{
    public List events { get; set; }
}

 

怎麼使用呢?以取出「Event[0]」的 replyToken 來說,就只要用以下的程式碼就行啦,是不是相當無腦呢?

   
RootObject rootObject = JsonConvert.DeserializeObject(strJSON);
Event event = rootObject.events[0];
string replyToken = event.replyToken;

 

Subscribe
Notify of
guest

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
huangsb
huangsb
6 years ago

在 Visual Studio 2013 以後就有內建 json 轉 class 的功能可用