首页 > 解决方案 > E0349:在使用 nlohmann-json 使用 JSON 时,没有运算符“=”匹配这些操作数

问题描述

nlohmann-json在 Visual Studio 上的 C++ 项目中使用,我发现了一个错误

E0349:no operator "=" matches these operands

在下面的代码中:

#include <nlohmann/json.hpp>
using json = nlohmann::json;


void myFunc(unsigned int** arr) {
    json j;
    j["myArr"] = arr;//E0349:no operator "=" matches these operands
}

怎么了 ?

另一方面,当我尝试以下方法时,它可以工作。

void myFunc(unsigned int** arr) {
    json j;
    j["myArr"] = {1,2,3};// no error
}

我猜这归因于数据类型问题。

我将不胜感激任何信息。

标签: c++jsonvisual-studionlohmann-json

解决方案


nlohmann json 仅支持从 c++ 标准库容器创建数组。不可能从指针创建数组,因为它没有关于数组大小的信息。

如果您有 c++20,那么您可以使用std::span将指针(和大小)转换为容器:

#include <nlohmann/json.hpp>
#include <span>

using json = nlohmann::json;


void myFunc(unsigned int* arr, size_t size) {
    json j;
    j["myArr"] = std::span(arr, size);
}

如果您没有 c++20,您将不得不std::span自己实现或将您的数组复制到类似的东西std::vector(或者只是使用std::vector开始而不是原始数组)。

或者手动构造数组(这里仍然需要一个大小):

void myFunc(unsigned int* arr, size_t size) {
    json j;
    auto& myArr = j["myArr"];
    for (size_t i = 0; i < size; i++)
    {
        myArr.push_back(arr[i]);
    }
}

推荐阅读