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

C++ Builder 10.2.3中如何从TJSONArray获取值?

解决C++ Builder 10.2.3中TJSONArray取值的链接错误与正确写法

错误原因分析

你遇到的[ilink64 Error] Unresolved external错误,核心问题有两个:

  1. 类型调用错误:TJSONValue本身没有泛型版GetValue<T>方法,该方法属于TJSONObject,直接通过TJSONValue*调用会导致编译器无法正确解析模板实例。
  2. 链接阶段缺失模板实例:C++ Builder 10.2.3对JSON模板方法的处理需要显式确保模板实例被编译,或者项目未正确关联System.Json库。

正确实现步骤与代码

1. 类型安全转换与空指针检查

先将解析后的TJSONValue*转换为TJSONObject*,再逐层获取数组和子项,同时添加空指针判断避免崩溃:

#include <System.Json.hpp>

System::Net::Httpclient::_di_IHTTPResponse response = NetHTTPRequest1->Get(L"https://url"); 

System::Json::TJSONValue* ResponseData = TJSONObject::ParseJSONValue(response->ContentAsString(TEncoding::UTF8));
UnicodeString Value = L"";

if (ResponseData && ResponseData->InheritsFrom(__classid(TJSONObject)))
{
    TJSONObject* RootObj = static_cast<TJSONObject*>(ResponseData);
    // 获取Item1对应的JSON数组
    TJSONValue* Item1Val = RootObj->GetValue(L"Item1");
    if (Item1Val && Item1Val->InheritsFrom(__classid(TJSONArray)))
    {
        TJSONArray* Item1Arr = static_cast<TJSONArray*>(Item1Val);
        // 检查数组是否有元素
        if (Item1Arr->Count > 0)
        {
            TJSONValue* FirstItem = Item1Arr->Items[0];
            if (FirstItem && FirstItem->InheritsFrom(__classid(TJSONObject)))
            {
                TJSONObject* SubItemObj = static_cast<TJSONObject*>(FirstItem);
                // 获取SubItem1的字符串值
                Value = SubItemObj->GetValue(L"SubItem1")->Value();
            }
        }
    }
}

// 使用Value后释放资源
delete ResponseData;

2. 解决链接错误的项目配置

如果上述代码仍出现链接错误,需检查项目配置:

  • 确认代码头部已添加#include <System.Json.hpp>。
  • 在项目的链接器选项中,添加对应平台的库文件:32位项目加SystemJson.lib,64位项目加SystemJson64.lib。
  • 若模板实例化仍有问题,可在代码中显式声明模板实例:
    template TJSONArray* TJSONObject::GetValue<TJSONArray>(const UnicodeString&);
    

关键说明

  • C++ Builder 10.2.3的JSON类库中,TJSONObject::GetValue<T>是模板方法,但TJSONValue无此方法,必须先转换为TJSONObject*才能调用。
  • 所有JSON对象/数组的转换都需要先判断类型(InheritsFrom),避免空指针或类型转换错误导致程序崩溃。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 22:33:16