0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

2015-07-25 c++ builder XE4, 10.2 Tokyo > JSON > ファイル書出し > AddPair() / ToString() | 2019-05-21 コードの間違い

0
Last updated at Posted at 2015-07-24
動作確認
C++ Builder XE4
C++ Builder 10.2 Tokyo

AddPair()にてキーと値を元にTJSONObjectに追加して、それをファイル書き出しする。

http://www.gesource.jp/weblog/?p=6067
にてDelphiで書かれているコードを参考にした。

# include <DBXJSON.hpp> // for JSON
# include <memory> // for unique_ptr

...
	TJSONObject *json;

	json = new TJSONObject();

	json->AddPair(L"name", L"John Smith");
	json->AddPair(L"age", L"33");

//	ShowMessage(json->ToString());

	std::unique_ptr<TStringList> sl(new TStringList);
	sl->Add( json->ToString() );
	sl->SaveToFile(L"test.json");

	json->Free();
test.json
{"name":"John Smith","age":"33"}

AddPair(L"key", NULL);
とした場合は、このペアは追加されないようだ。

コードの間違い

(追記 2019/05/21)

上記の実装ではjson->Free();としている。
delete json;が正しいだろう。

Never directly call TObject::Free() in C++, use the delete operator instead:

# include <DBXJSON.hpp> // for JSON
# include <memory> // for unique_ptr

...
    TJSONObject *json;

    json = new TJSONObject();

    json->AddPair(L"name", L"John Smith");
    json->AddPair(L"age", L"33");

//  ShowMessage(json->ToString());

    std::unique_ptr<TStringList> sl(new TStringList);
    sl->Add( json->ToString() );
    sl->SaveToFile(L"test.json");

    delete json;

10.2 Tokyo対応 (2019-05-29)

10.2 Tokyoになり、インクルードファイルが変わった。

.cpp
# include <System.JSON.hpp>
# include <memory>

void __fastcall TForm1::Button2Click(TObject *Sender)
{
	TJSONObject *json;

	json = new TJSONObject();

	json->AddPair(L"name", L"John Smith");
	json->AddPair(L"age", L"33");

//  ShowMessage(json->ToString());

	std::unique_ptr<TStringList> sl(new TStringList);
	sl->Add( json->ToString() );
	sl->SaveToFile(L"test.json");

	delete json;
}
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?