You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#中将currentTimeUn变量传入JSON字符串的DateMax字段?

如何在C#中将变量值传入JSON字符串的指定字段?

你现在的问题是直接在JSON字符串里写{currentTimeUn},但C#并不会自动识别这个变量并替换它的值。这里有几种靠谱的解决方法:

方法一:使用字符串插值(最直接)

C# 6及以上版本支持字符串插值,只需要给字符串加上$前缀,就能直接在大括号里写变量名完成替换,非常方便:

Int32 unixTimestamp = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds; 
Console.Write(unixTimestamp); 
var currentTimeUn = unixTimestamp.ToString(); 
// 加$前缀开启插值,JSON本身的大括号要写双份{{}}避免被当成插值占位符
string json = $"{{ \"Method\": \"GetShippedOrders\",\"Params\": {{ \"DateMin\": 1575158400, \"DateMax\": {currentTimeUn} }} }}"; 

方法二:使用String.Format(兼容旧版C#)

如果你的项目还在使用C# 6以下的版本,用String.Format也能实现变量替换:

Int32 unixTimestamp = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds; 
Console.Write(unixTimestamp); 
var currentTimeUn = unixTimestamp.ToString(); 
// 用{0}作为占位符,最后把变量作为参数传入
string json = String.Format("{{ \"Method\": \"GetShippedOrders\",\"Params\": {{ \"DateMin\": 1575158400, \"DateMax\": {0} }} }}", currentTimeUn); 

方法三:使用JSON序列化(最推荐)

手动拼接JSON很容易因为引号、大括号写错出问题,更规范的做法是先定义对应的数据类,再通过序列化生成JSON:

先定义匹配JSON结构的类:

public class OrderRequestParams
{
    public int DateMin { get; set; }
    public int DateMax { get; set; }
}

public class OrderRequest
{
    public string Method { get; set; }
    public OrderRequestParams Params { get; set; }
}

然后生成对象并序列化(.NET Core 3.0+自带System.Text.Json,.NET Framework可以用Newtonsoft.Json):

Int32 unixTimestamp = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds; 
var request = new OrderRequest
{
    Method = "GetShippedOrders",
    Params = new OrderRequestParams
    {
        DateMin = 1575158400,
        DateMax = unixTimestamp
    }
};
// 自动生成格式正确的JSON
string json = System.Text.Json.JsonSerializer.Serialize(request);

这种方法不仅可读性更高,还能避免手动拼接时的语法错误,后续修改字段也更灵活。

内容的提问来源于stack exchange,提问作者Brad Playdon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 19:32:46