- Notifications
You must be signed in to change notification settings - Fork47
Creation a JSON object with data of different types and run serialization and deserialization of JSON data.
License
vivazzi/JAson
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
Realization of JSON protocol in mql4 / mql5.You can create JSON object with data of different types and run serialization and deserialization of JSON data.
This repo is fork ofJAson (https://www.mql5.com/en/code/13663) with improvements, refactoring code, unit tests and translating of comments to English.
Download repo and copyJAson/Include/JAson.mqh
folder to<TERMINAL DIR>/MQL(4/5)/Include
Add#include <JAson.mqh>
and createCJAVal
object to work with JSON data. See simple example for easy understand:
#include<JAson.mqh>intOnInit(){CJAValdata;// --- simple structure ---data["a"] =12;data["b"] =3.14;data["c"] ="foo";data["d"] =true;Print(data["a"].ToInt());// 12Print(data["b"].ToDbl());// 3.14Print(data["c"].ToStr());// "foo"Print(data["d"].ToBool());// true// --- array structure ---data["e"].Add("bar");data["e"].Add(2);Print(data["e"][0].ToStr());// "bar"Print(data["e"][1].ToInt());// 2// --- nested structures ---// - as part of array -CJAValsub_data_obj_in_list;sub_data_obj_in_list["k1"] =7;sub_data_obj_in_list["k2"] ="baz";data["e"].Add(sub_data_obj_in_list);Print(data["e"][2]["k1"].ToInt());// 7Print(data["e"][2]["k2"].ToStr());// "baz"// - as object -CJAValsub_data_obj;sub_data_obj["sub_c"] ="muz2";sub_data_obj["sub_d"] =44;data["f"] =sub_data_obj;Print(data["f"]["sub_c"].ToStr());// "muz2"Print(data["f"]["sub_d"].ToInt());// 44}
To get value from Json object, you need use methods:
ToInt()
forinteger
type;ToDbl()
fordouble
type;ToStr()
forstring
type;ToBool()
forboolean
type;
For example:
data["a"].ToInt();// 12data["b"].ToDbl();// 3.14data["c"].ToStr();// "foo"data["d"].ToBool();// true
To create array, use.Add()
data["e"].Add("bar");data["e"].Add(2);
To use nested json, create otherCJAVal
object and assign to existedCJAVal
object. NestedCJAVal
object can be value of key or contained in array:
CJAValdata;// - adding as object -CJAValdata_1;data_1["d1_1"] =7;data_1["d1_2"] ="foo";data["a"] =data_1;// - adding as part of array -CJAValdata_2;data_2["d2_1"] =1;data_2["d2_1"] ="bar";data["b"].Add("buz");data["b"].Add(data_2);data["b"].Add("muz");
JAson provides the serialization and deserialization:
#include<JAson.mqh>intOnInit(){stringdata_str;CJAValdata;data["a"] =3.14;data["b"] ="foo";data["c"].Add("bar");data["c"].Add(2);data["c"].Add("baz");Print(data["b"].ToStr());// foodata_str =data.Serialize();Print(data_str);// {"a":3.14000000,"b":"foo","c":["bar",2,"baz"]}CJAValdata_2;data_2.Deserialize(data_str);Print(data_2["a"].ToDbl());// 3.14Print(data_2["b"].ToStr());// fooPrint(data_2["c"][0].ToStr());// barPrint(data_2["c"][1].ToInt());// 2Print(data_2["c"][2].ToStr());// baz}
It can be useful for data saving in a file or send Json object by POST request.
POST request with Json object:
#include<JAson.mqh>#include<requests/requests.mqh>// https://github.com/vivazzi/mql_requestsintOnInit(){CJAValdata;data["a"] =7;data["b"] ="foo";Requestsrequests;Responseresponse =requests.post("https://vivazzi.pro/test-request/",data.Serialize());Print(response.text);// {"status": "OK", "method": "POST", "body": "{"a": 7, "b": "foo"}"}data.Deserialize(response.text);Print(data["status"].ToStr());// "OK"Print(data["method"].ToStr());// "POST"Print(data["body"].ToStr());// {"a": 7, "b": "foo"}// if Json object has value of key as serialized object, you can also deserialize this valueCJAValdata_2;data_2.Deserialize(data["body"].ToStr());Print(data_2["a"].ToInt());// 7Print(data_2["b"].ToStr());// "foo"// also you can join this Json objects to get full structuredata["body"] =data_2;Print(data["body"]["a"].ToInt());Print(data["body"]["b"].ToStr());}
In this example it has been used:mql_requests and online serviceGetest for testing GET and POST requests.
To clearCJAVal
object, use methodClear()
:
#include<JAson.mqh>intOnInit(){CJAValdata;stringdata_str;data["a"] =3.14;data["b"] ="foo";data_str =data.Serialize();Print(data_str);// "{"a":3.14000000,"b":"foo"}"data.Clear();data["c"] =123;data["d"] ="bar";data_str =data.Serialize();Print(data_str);// "{"c":123,"d":"bar"}"}
So if you want to get values of "c" and "d" keys, you need:
Print(data["c"].ToInt())// 123Print(data["d"].ToStr())// "bar"
But if you check "a" and "b" keys, that no longer exist (or never used keys), you get initial values for key:
// old notexistent keysPrint(data["a"].ToDbl())// 0.0Print(data["b"].ToStr())// "" (empty)// never used keysPrint(data["e"].ToStr())// "" (empty)
And this can lead to logical errors - be careful! Always use only a specific set of keys to avoid logical error!
If you use Json, that can be cleaned up, and you use different keys, you can check type of keys. JAson library define next types:
jtUNDEF
, if key is undefinedjtNULL
forNULL
jtBOOL
forboolean
jtINT
forint
jtDBL
fordouble
jtSTR
forstring
jtARRAY
forarray
jtOB
forobj
Then in example above:
// old notexistent keysPrint(data["a"].ToDbl());// 0.0Print(data["a"].type);// jtUNDEFPrint(data["b"].ToStr());// ""Print(data["b"].type);// jtUNDEF// current keysPrint(data["c"].ToInt());// 123Print(data["c"].type);// jtINTPrint(data["d"].ToStr());// "bar"Print(data["d"].type);// jtSTR// never used keysPrint(data["e"].ToStr());// ""Print(data["e"].type);// jtUNDEF
So you can compare key type withjtUNDEF
, if you want to check for the existence of a key:
#include<JAson.mqh>intOnInit(){CJAValdata;data["a"] =3.14;data.Clear();data["c"] =123;if (data["a"].type ==jtUNDEF) {// do something }else {// else do something }}
CJAVal data;
- CreatesCJAVal
(Json) object.CJAVal data(CJAVal* a_parent, enJAType a_type);
- CreatesCJAVal
object with specified type.a_parent
- parent for createdCJAVal
object (useNULL
if no parent).a_type
- type ofCJAVal
object, available types:jtUNDEF
,jtNULL
,jtBOOL
,jtINT
,jtDBL
,jtSTR
,jtARRAY
,jtOBJ
.CJAVal data(const double v, int precision=-100);
- CreatesCJAVal
object of double type of specified precision.
data[key] = some_val;
- Addssome_val
(int, double, string or anotherCJAVal
) to data withkey
key.data[key].Add(other_data);
- Addsother_data
(int, double, string or other CJAVal) tokey
array.data[key].Add(const double v, int precision=-2);
- Addsv
of double type with specified precision tokey
array.
data.Serialize();
- ConvertCJAVal
object to string.data.Deserialize(string json, int acp=CP_ACP);
- Convertjson
string toCJAVal
object.data
gets result.acp
- code page for deserialization.
data.Clear(enJAType jt=jtUNDEF, bool save_key=false);
- ClearsCJAVal
object.jt
- sets specified type ofCJAVal
object.save_key
- iftrue
, values of all keys will be keys will be cleared, else all keys and values will be cleared.data.Size();
- Gets size ofCJAVal
object.
- If the
dbl_precision
value is in the range from 0 to 16, then a string representation of the number with the specified number of decimal places will be obtained. - If the
dbl_precision
value is in the range from -1 to -16, then the string representation of the number in scientific format with the specified number of decimal places will be obtained. - In all other cases, the string representation of the number will contain 8 decimal places.
- Copy
JAson/Scripts/
folder to<TERMINAL DIR>/MQL(4/5)/Scripts/
- Compile
TestJAson.mq4
and runTestJAson.ex4
in terminal in a window of any trading pair. - Look test result in
<TERMINAL DIR>/MQL(4/5)/Files/TestJAson_unit_test_log.txt
To reporting bugs or suggest improvements, please use theissue tracker.
Thank you very much, that you would like to contribute toJAson. Thanks to thepresent, past and future contributors.
If you think you have discovered a security issue in code, please do not create issue or raise it in any public forum until we have had a chance to deal with it.For security issues usesecurity@vuspace.pro
- Report bugs and suggest improvements:
- https://github.com/vivazzi/JAson/issues (strongly recommended)
- https://www.mql5.com/en/code/13663 (not tracked by the repo author)
- Author's site of this repo, Artem Maltsev:https://vivazzi.pro
Copyright © 2021 Alexey Sergeev, Artem Maltsev andcontributors.
MIT licensed.
About
Creation a JSON object with data of different types and run serialization and deserialization of JSON data.