nlohmann/json

ohos model to json string garbage characters

SenyiWong opened this issue · 5 comments

Description

微信截图_20241030172000
微信图片编辑_20241030155950

Reproduction steps

100% reproduction

Expected vs. actual results

struct Person {
std::string name;
int age;
NLOHMANN_DEFINE_TYPE_INTRUSIVE(Person, name, age)
};

Person person;
person.name = "中文字符";
person.age = 23;
nlohmann::json js = person;
const char *str = js.dump().c_str();

js.dump().c_str(); This will make the string garbled

but js.dump() assignment to std::string show the correct string

Minimal code example

No response

Error messages

No response

Compiler and operating system

ohos 5.0

Library version

current version

Validation

picture 1 is android ndk
picture 2 is ohos ndk

person.name = "中文字符";

Is this UTF-8? This library requires all strings to be UTF-8.

Please add a complete code example and not just images.

// Person.h

#include <string>
#include <nlohmann/json.hpp>
 
struct Person {
    std::string name;
    int age;
    NLOHMANN_DEFINE_TYPE_INTRUSIVE(Person, name, age)
};
/**********************************************************************************************/

// napi_init.cpp  ohos IDE generate template class
// this will retrieve the correct JSON. 

static napi_value GetJson(napi_env env, napi_callback_info info) {
    Person person;
    person.name = "apple"; 
    person.age = 26;
    
    nlohmann::json js = person;
    std::string jsstr = js.dump();
    const char *str = jsstr.c_str();
    
    size_t length = NAPI_AUTO_LENGTH;                                        
    napi_value result = nullptr;
    napi_status status = napi_create_string_utf8(env, str, length, &result);
    if (status != napi_ok) {
        napi_throw_error(env, nullptr, "Failed to create UTF-8 string");
        return nullptr;
    }
    return result;
}

/**********************************************************************************************/
// js.dump().c_str(); will happen string garbled code

static napi_value GetJson(napi_env env, napi_callback_info info) {
    Person person;
    person.name = "apple"; 
    person.age = 26;
    
    nlohmann::json js = person;
    const char *str = js.dump().c_str();
    
    size_t length = NAPI_AUTO_LENGTH;                                        
    napi_value result = nullptr;
    napi_status status = napi_create_string_utf8(env, str, length, &result);
    if (status != napi_ok) {
        napi_throw_error(env, nullptr, "Failed to create UTF-8 string");
        return nullptr;
    }
    return result;
}

With

const char *str = js.dump().c_str();

you store a pointer to a temporary that survives the lifetime of the temporary js.dump(), leaving a dangling pointer.

Hence, the code

std::string jsstr = js.dump();
const char *str = jsstr.c_str();

works, because now str is valid as long as jsstr is.

This is not a library issue.