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

VB中如何正确向JSON字符串插入变量以避免400错误请求

你遇到400错误通常有两个核心原因:一是插入变量时未处理JSON特殊字符(双引号、换行、斜杠等)导致最终JSON格式非法;二是字段类型和接口要求不匹配,比如你原代码里把布尔值、数字都加了双引号当成字符串传输,部分严格的接口会直接拒绝。

最优方案:使用JSON序列化库生成(推荐)

优先用专门的JSON序列化工具生成字符串,完全不需要手动处理格式和转义,不会出现语法错误。以.NET环境常用的序列化库为例,首先定义和JSON结构匹配的类:

Public Class TransactionRequest
    Public Property StoreId As String
    Public Property TerminalId As String
    ' 如果接口要求布尔/数字类型,把对应属性的类型改成Boolean/Decimal即可
    Public Property CaptureMode As String
    Public Property MerchantReferenceCode As String
    Public Property InvoiceNumber As String
    Public Property TimeoutMinutes As String
    Public Property ShowAddress As String
    Public Property AddressRequired As String
    Public Property TransactionTotal As String
    Public Property TaxTotal As String
    Public Property CustomerCode As String
End Class

然后给属性赋值后直接序列化即可,变量直接传入不需要额外处理:

' 这里的yourVariable就是你要插入的MerchantReferenceCode变量值
Dim requestData As New TransactionRequest With {
    .StoreId = "12345",
    .TerminalId = "12345",
    .CaptureMode = "true",
    .MerchantReferenceCode = yourVariable,
    .InvoiceNumber = "12345",
    .TimeoutMinutes = "5",
    .ShowAddress = "true",
    .AddressRequired = "true",
    .TransactionTotal = "33.33",
    .TaxTotal = "2.00",
    .CustomerCode = "12345"
}

' 序列化为标准JSON字符串
Dim myJSON As String = JsonConvert.SerializeObject(requestData)

临时方案:手动拼接时对变量做转义

如果受项目限制无法使用序列化库,需要先对插入的变量做JSON特殊字符转义后再拼接:
首先写转义工具函数:

Function EscapeJson(rawValue As String) As String
    Return rawValue.Replace("\", "\\").Replace("""", "\""").Replace(vbCr, "\r").Replace(vbLf, "\n").Replace(vbTab, "\t")
End Function

然后拼接时使用转义后的变量:

Dim yourVariable As String = "你要插入的变量内容"
Dim escapedValue As String = EscapeJson(yourVariable)
Dim myJSON As String = "{""StoreId"":""12345"",""TerminalId"":""12345"",""CaptureMode"":""true"",""MerchantReferenceCode"":""" & escapedValue & """,""InvoiceNumber"":""12345"",""TimeoutMinutes"":""5"",""ShowAddress"":""true"",""AddressRequired"":""true"",""TransactionTotal"":""33.33"",""TaxTotal"":""2.00"",""CustomerCode"":""12345""}"

内容的提问来源于stack exchange,提问作者Rick Walker

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 00:24:04