C++处理json数据注意点(url传递接收json数据)

json结构(字符串类型):

{"data" : 
    {
        "face_token" : "f94420d0e7ebc665d64d5bchgcf457",
        "log_id" : "6467456563",
        "result" : 
        [
            {
                "group_id" : "122222",
                "score" : 90.92,
                "user_id" : "K34545665"
            }
        ],
        "result_num" : 1
    },
    "errno" : 0,
    "msg" : "success"
}

问题记录

1.

    json jsonResult = json::parse(res); //解析json响应
    const std::string user =jsonResult["data"]["result"]["user_id"].get<std::string>();
    std::cout<< user <<std::endl;

报错:terminate called after throwing an instance of 'nlohmann::json_abi_v3_11_3::detail::type_error'
  what():  [json.exception.type_error.305] cannot use operator[] with a string argument with array
./run.sh: line 27: 19103 Aborted                 (core dumped) ./build/face_offline_sdk

分析解决:

尝试使用 operator[] 来从一个 JSON 数组中访问元素,但是提供了一个字符串作为参数。在 nlohmann/json 库中,当你使用 operator[] 与一个字符串参数时,它期望所访问的 JSON 对象是一个对象(键值对集合),而不是数组。

jsonResult["data"]["result"] 是一个数组,而不是一个对象。在 JSON 中,数组的元素可以通过索引访问,而不是通过键名。

"result" : 
        [
            {
                "group_id" : "122222",
                "score" : 90.92,
                "user_id" : "K34545665"
            }
        ]

result应该是一个数组,{
                "group_id" : "122222",
                "score" : 90.92,
                "user_id" : "K34545665"
            }是第一个元素,因此用["result"][0]["user_id"]访问

    json jsonResult = json::parse(res); //解析json响应

    const std::string user =jsonResult["data"]["result"][0]["user_id"];

Nlohmann.Json处理库:

include引入:

#include <nlohmann/json.hpp>


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值