1. 程式人生 > >C#-Newtonsoft.Json生成複雜JSON

C#-Newtonsoft.Json生成複雜JSON

官方文件:https://www.newtonsoft.com/json/help/html/SerializeObject.htm

一種方式就可以生成所有的JSON
Collection -> 陣列
Object
, Dictionary -> 物件

PS:Dictionary不用根據資料格式建立類但但複用性不好,Object需要根據資料格式建立類但複用性好也能用get,set處理屬性

例如:

/*
介面格式:
{
    code:返回結果狀態
    message:訊息
    data:[
        {
            provider:提供者
            name:資料名稱,
            description:[
                {key:***,value:***}
                {key:***,value:***}
            ],
            download:下載,
            thumbnail:縮圖,
            detail:詳情
        }
    ]
}
*/

Dictionary<String, Object> data = new Dictionary<String, Object>
{
    {"code", 0},
    {"message", ""},
    {"data", new List<Object>{
        new Dictionary<String, Object>{
            {"provider", "提供者"},
            {"name", "古生物化石資料"},
            {"description", new List<Object>{
                new Dictionary<String, String>{
                    {"key", "xxx"},
                    {"value", "xxx"}
                },
                new Dictionary<String, String>{
                    {"key", "xxx"},
                    {"value", "xxx"}
                }
            }},
            {"download", ""},
            {"thumbnail", ""},
            {"detail", ""},
        }
    }}
};

String json = JsonConvert.SerializeObject(data, Formatting.Indented);