ASP.NET C# POST 參數字串 VS 參數物件

若時常在API串接,常常會遇到要拼裝POST參數資料(application/json)
看到比較古老的系統都會用字串拼裝方式
短字串還可以,但字串一長會有拼錯與難以閱讀的困境
因此可以使用物件方式建立參數並轉成字串

using Newtonsoft.Json;

int id = 1;

// 物件拼裝
string postdata = JsonConvert.SerializeObject(new
{
    id = id,
    name = "小美",
    @params = new
    {
        amount = 9987,
        age = 25,
        job = "Programmer"
    }
});

Console.WriteLine(postdata);
// output: {"id":1,"name":"小美","params":{"amount":9987,"age":25,"job":"Programmer"}}

// 字串拼裝
string postdata = $"{{\"id\":\"{id}\",\"name\":\"小美\",\"params\":{{\"amount\":9987,\"age\":25,\"job\":\"Programmer\"}}}}";

Console.WriteLine(postdata);
// output: {"id":1,"name":"小美","params":{"amount":9987,"age":25,"job":"Programmer"}}

 

留言

Top