首页 > 解决方案 > 在 mql5 中处理 json 字符串

问题描述

我收到了以下字符串:

{'1.128330': {'sell': {'id': '1', 'got': 93.03059560034244}, 'buying': {'id': '2', 'got': 80.29916788508336}}, '1.128520': {'sell': {'id': '1', 'got': 16.857589570319895}, 'buying': {'id': '2', 'got': 225.53801097382126}}, '1.128480': {'sell': {'id': '1', 'got': 25.107832004252355}, 'buying': {'id': '2', 'got': 173.6565182150294}}, '1.128600': {'sell': {'id': '1', 'got': 5.970539130416359}, 'buying': {'id': '2', 'got': 361.9910279494408}}, '1.128640': {'sell': {'id': '1', 'got': 2.5341625886266863}, 'buying': {'id': '2', 'got': 393.3836268867237}}, '1.128020': {'sell': {'id': '1', 'got': 428.3577531480875}, 'buying': {'id': '2', 'got': None}}}

我不明白如何在 mql5 中处理和分离 json 的值,因为没有库足够高效来提供帮助。
我愿意得到输出:

price[] = {1.128330,1.128520,1.128480,1.128600,1.128640,1.128020}
whatdo[] = {1,2,1,2,1,2,1,2,1,2,1,2}
gain[] = {93.03059560034244,80.29916788508336,16.857589570319895,225.53801097382126,25.107832004252355,173.6565182150294,5.970539130416359,361.9910279494408,2.5341625886266863,393.3836268867237,428.3577531480875,0}

请让我知道我能做什么。

标签: mql5metatrader5

解决方案


您可以尽可能多地使用“本机”解决方案。应该对您有好处,但请记住,它不处理 json-arrays,您应该遍历数组元素。这是一个带有示例的链接

如果我是你,我会这样编码:

 #include <jason.mqh>
 string receivedJson="{'1.128330': {'sell': {'id': '1', 'got': 93.03059560034244}, 'buying': {'id': '2', 'got': 80.29916788508336}}, '1.128520': {'sell': {'id': '1', 'got': 16.857589570319895}, 'buying': {'id': '2', 'got': 225.53801097382126}}, '1.128480': {'sell': {'id': '1', 'got': 25.107832004252355}, 'buying': {'id': '2', 'got': 173.6565182150294}}, '1.128600': {'sell': {'id': '1', 'got': 5.970539130416359}, 'buying': {'id': '2', 'got': 361.9910279494408}}, '1.128640': {'sell': {'id': '1', 'got': 2.5341625886266863}, 'buying': {'id': '2', 'got': 393.3836268867237}}, '1.128020': {'sell': {'id': '1', 'got': 428.3577531480875}, 'buying': {'id': '2', 'got': None}}}"

 double price[], gain[]; int what2do[];
 if(!processJson(receivedJson))print("error");

 boolean processJson(string inputJson,double &price[],double &gain[],int what2do[])
   {
    CJAVAL json(NULL, jtUNDEF);
    if(!json.Deserialize(inputJson))
        return(false);
    if(ArrayResize(price,json.m_e)==-1 || ArrayResize(gain,json.m_e)==-1 || ArrayResize(what2do,json.m_e)==-1)
        return(false);
    const string sell="sell", buy="buy", got="got", none="None";
    for(int i=0;i<json.m_e;i++)
      {
       price[i]=(double)json.m_e[i].m_key.ToDouble();
       for(int int j=0;j<json.m_e[i].m_e;j++)
         {
          string cmd=(int)json.m_e[i].m_e[j];
          what2do[i]=(cmd==sell ? 2 : (cmd==buy ? 1 : 0) );
          string gain=json.m_e[i].m_e[j][got];
          gain[i]=gain==none ? INT_MIN : DoubleToString(gain);
         }
      }
    return(true);
   }

推荐阅读