带有utf16字符的json字符串无法从'const char [566]'转换为'std :: basic_string< _Elem,_Traits,_Ax>'

时间:2017-04-09 16:58:51

标签: json utf-16 c++98

我有json需要测试一个包含utf16宽字符的字符串但是我收到以下错误消息:

\..\test\TestClass.cpp(617): error C2440: 'initializing' : cannot convert from 'const char [566]' to 'std::basic_string<_Elem,_Traits,_Ax>'


     with
2>          [
2>              _Elem=wchar_t,
2>              _Traits=std::char_traits<wchar_t>,
2>              _Ax=std::allocator<wchar_t>
2>          ]
2>          No constructor could take the source type, or constructor overload resolution was ambiguous

这是我的json:

static std::wstring& BAD_JSON5_missingComma_multipleNewlines_Utf16MixedDosAndUnixLineEndings()
    {
        static std::wstring j =
        "{\n"           <=VS squigly says error on this line
            "\"header\":{\n"
                "\"version\":{\"major\":1,\"minor\":0,\"build\":0}\n"
            "},\n"
            "\"body\":{\n"
                "\"string\":{\"type\":\"OurWideStringClass\",\"value\":\"foo\"},\n\n\n\n"
                "\"int\":[\n"
                    "{\"type\":\"string\",\"value\":\"\\u9CE5\"},\n"
                    "{\"type\":\"Int\",\"value\":5678}\n"
                "],\n"
                "\"double\":{\"type\":\"Double\",\"value\":12.34},\n"
                "\"path1\":[\n"
                    "{\n"
                        "\"string\":{\"type\":\"OurWideStringClass\",\"value\":\"bar\"},\r\n"
                        "\"int\":[\n"
                            "{\"type\":\"Int\"\"value\":7},\n"
                            "{\"type\":\"Int\",\"value\":11}\n"
                        "]\n"
                    "},\n"
                    "{\n"
                        "\"string\":{\"type\":\"OurWideStringClass\",\"value\":\"top\"},\n"
                        "\"int\":[\n"
                            "{\"type\":\"Int\",\"value\":13},\r\n"
                            "{\"type\":\"Int\",\"value\":41}\n"
                        "]\n"
                    "}\n"
                "],\n"
                "\"path2\":{\n"
                    "\"int\":{\"type\":\"Int\",\"value\":-1234},\n"
                    "\"double\":{\"type\":\"Double\",\"value\":-1.234}\r\n"
                "}\n"
            "}\n"
        "}\n"; <=double clicking build error goes to this line

        return j;
    }

这就是它的使用方式

OurWideStringClass slxStJson5 = BAD_JSON5_missingComma_multipleNewlines_Utf16MixedDosAndUnixLineEndings();
std::wistringstream ssJsonMissingCommaUtf16Newlines(slxStJson5);

我以为我的json中的wchar_t覆盖了std :: wstring。有什么想法是什么问题?你可以在\ u9ce5中看到我的utf16角色。这是此测试的关键。

我查看了这个c2440但是没有看到他们在UDT决议中提到的内容。

我正在看它前面的这个which puts an L ,但是对于逃脱的c字符串,我不知道把L放在哪里。

1 个答案:

答案 0 :(得分:1)

std::wstring无法从"my string" std::wstring初始化,因此编译错误。

您可以从narrow string literal初始化L - 其语法包括开头引号之前的 L"my string"前缀,,例如L

当您使用字符串文字串联时,需要在所有字符串文字前加static std::wstring j = L"{\n" L"\"header\":{\n" L"\"version\":{\"major\":1,\"minor\":0,\"build\":0}\n" L"},\n" ... ,即:

{{1}}