nlohmann / json

JSON for Modern C++
https://json.nlohmann.me
MIT License
42.18k stars 6.65k forks source link

Class Composition of json members produces incorrect json when constructing with initialization list #3955

Closed killerswin2 closed 1 year ago

killerswin2 commented 1 year ago

Description

When using Composition of types in a class for json abstraction, constructing the class produces wrong incorrect json when using an initialization list. Passed json objects/docs seem to be pushed back in the json object attribute attached to the class.

Reproduction steps

just call the class constructor of your class and pass in the json object.

Expected vs. actual results

[[10,20,30,40,{"apple":20}]] with initialization list construction.

[10,20,30,40,{"apple":20}] without, manually assign the member attribute to be

Minimal code example

#include <iostream>
#include <string>
#include <nlohmann/json.hpp>

class game_data_json_array
{
public:
    game_data_json_array(nlohmann::json object) : jsonArray{ object } {}        // produces [[10,20,30,40,{"apple":20}]]
    nlohmann::json jsonArray;
};

class game_data_json_array2
{
public:
    game_data_json_array2(nlohmann::json object) {
        jsonArray = object;                 // produces [10,20,30,40,{"apple":20}]
    }
    nlohmann::json jsonArray;
};

// json 
/*
[
  10,
  20,
  30,
  40,
  {"apple": 20}
]

*/

int main(void)
{
    nlohmann::json jsonArray = nlohmann::json::parse(R"([
  10,
  20,
  30,
  40,
  {"apple": 20}
])");
    game_data_json_array test1 = game_data_json_array(jsonArray);
    game_data_json_array2 test2 = game_data_json_array2(jsonArray);

    std::cout << test1.jsonArray;

    std::cout << "\n";

    std::cout << test2.jsonArray;

    return 0;
}

Error messages

N/A

Compiler and operating system

Windows 10, msvc 1935

Library version

3.11.2

Validation

gregmarr commented 1 year ago

See if this first FAQ entry answers your question: https://json.nlohmann.me/home/faq/

killerswin2 commented 1 year ago

oof, that's what I get for not reading the faq