C++ Builder 10.2 Tokyo > はまりポイント > TStringList > DelimitedText使用時に \"は消える


動作環境
RAD Studio 10.2 Tokyo Update 3

概要

  • JSON文字列を置換する処理を実装中、エラーに遭遇
  • 調査の結果、\"が消えていることが分かった
  • TStringListをDelimitedTextで分割したときに消える

再現コード

Unit1.cpp
//---------------------------------------------------------------------------

#include <vcl.h>
#pragma hdrstop

#include <memory>
#include "Unit1.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
    : TForm(Owner)
{
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
    String astr = L"\"AAA\",\"BBB\",\"CCC\"";

    Memo1->Lines->Add(astr);

    std::unique_ptr<TStringList> wrkSL(new TStringList);
    wrkSL->StrictDelimiter = true;
    wrkSL->Delimiter = ',';
    wrkSL->DelimitedText = astr;

    String res = L"";
    res += wrkSL->Strings[0];
    res += L",";
    res += wrkSL->Strings[1];
    res += L",";
    res += wrkSL->Strings[2];

    Memo1->Lines->Add(res);
}
//---------------------------------------------------------------------------

結果

備考

  • JSON文字列の処理をする場合、先に\"を消して、処理後に付けるなどの工夫が必要になるのだろう
  • JSON文字列に対して処理した時に下記の事例も見つかった
    • 一つ目のKeyには\"が付いている
    • 二つ目以降のKeyには\"が付いていない
    • こちらの実装によるミスかもしれないが

下記の一つ目はDelimitedTextを使わない場合。
二つ目はDelimitedTextを使った場合。
ともに、文字列置換をしているが、片方で失敗している。

{ u"{\"name\":\"John Smith\",age,:\"33\",place,:\"Sydney\"}" }
{ u"{\"name\":\"7of9\",\"age\":\"79\",\"place\":\"Sydney\"}" }

一つ目について、nameは(")で囲われており、ageとplaceは囲われていない。