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

Inno Setup读取JSON对象指定字符串时遇格式异常求助

问题解决与方案

一、Inno JSON Config读取异常:仅显示'String'且缺失后缀

问题原因

大概率是读取JSON值时误用了类型判断函数而非取值函数,或是JSON节点类型不匹配、变量转换逻辑错误。

修复步骤

  1. 确认JSON结构:确保items.json中PathForNextFile为字符串类型,示例结构:
{
  "PathForNextFile": "String123.json"
}
  1. 修正Pascal读取代码:使用TJsonConfig.GetValue直接获取字符串值,避免错误调用类型相关函数:
var
  JSONConfig: TJsonConfig;
  NextFilePath: String;
begin
  JSONConfig := TJsonConfig.Create(nil);
  try
    JSONConfig.FileName := ExpandConstant('{src}\items.json'); // 用绝对路径避免文件找不到
    NextFilePath := JSONConfig.GetValue('PathForNextFile', ''); // 第二个参数为默认值
    Log('PathForNextFile: ' + NextFilePath);
  finally
    JSONConfig.Free;
  end;
end;

若JSON存储的是Unicode字符串,需将WideString转为String:

NextFilePath := AnsiString(JSONConfig.GetWideStringValue('PathForNextFile', ''));

二、用PowerShell实现读取(仅用String类型)

PowerShell默认字符串为Unicode,可通过编码转换转为Ansi String(对应Pascal的String),脚本示例:

# 读取并解析JSON文件
$jsonData = Get-Content -Path '.\items.json' -Raw | ConvertFrom-Json
$rawPath = $jsonData.PathForNextFile

# 转换为Ansi String(使用系统默认编码)
$ansiEncoding = [System.Text.Encoding]::Default
$ansiBytes = $ansiEncoding.GetBytes($rawPath)
$ansiPath = $ansiEncoding.GetString($ansiBytes)

# 输出结果
Write-Host "PathForNextFile: $ansiPath"

三、koldev JsonParser Library 使用指南

前置准备

将JsonParser.pas文件放入Inno Setup的脚本目录,在安装脚本顶部添加引入:

#include "JsonParser.pas"

读取JSON示例代码

var
  Parser: TJsonParser;
  RootNode, PathNode: TJsonNode;
  NextFilePath: String;
begin
  Parser := TJsonParser.Create;
  try
    // 加载JSON文件
    if not Parser.LoadFromFile(ExpandConstant('{src}\items.json')) then
    begin
      Log('Failed to load items.json');
      Exit;
    end;

    // 定位目标节点
    RootNode := Parser.Root;
    PathNode := RootNode.FindNode('PathForNextFile');
    
    // 验证节点类型并取值(转成String)
    if Assigned(PathNode) and (PathNode.NodeType = jntString) then
    begin
      NextFilePath := AnsiString(PathNode.Value); // WideString转String
      Log('PathForNextFile: ' + NextFilePath);
    end
    else
    begin
      Log('PathForNextFile node not found or is not a string');
    end;
  finally
    Parser.Free;
  end;
end;

关键说明

  • TJsonParser.LoadFromFile:加载指定路径的JSON文件
  • FindNode:从根节点递归查找目标节点
  • 节点值默认是WideString类型,通过AnsiString()强制转换为String;注意:若字符串含Ansi编码外的字符,会出现乱码或内容丢失。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 07:05:27