JSON Parser

0
(0)
Name:
JSON Parser
Author: ydrol (2014.02.24 07:27)
Downloaded: 26
Download:
JSON Parser 1
 json.mqh (23.9 Kb) View
Author:

Andrew Lord

Description:

This parses mql4 strings that contain JSON code. It creates a JSONValue that can be used to retrieve the fields within the JSON structure. It also provides a JSONIterator class to loop over object keys.

It parses the JSON using a simple a recursive descent parser. It requires the Hash class.

I still have to implement the parsing of unicode escaped characters.

The Codebase version might not be the most recent. The latest version can be found here.

Documentation:

JSONParser class

JSONValue class

 

Example:

#include "hash.mqh"
#include "json.mqh"

string s = "{ \"firstName\": \"John\", \"lastName\": \"Smith\", \"age\": 25, "+
"\"address\": { \"streetAddress\": \"21 2nd Street\", \"city\": \"New York\", \"state\": \"NY\", \"postalCode\": \"10021\" },"+
" \"phoneNumber\": [ { \"type\": \"home\", \"number\": \"212 555-1234\" }, { \"type\": \"fax\", \"number\": \"646 555-4567\" } ],"+
" \"gender\":{ \"type\":\"male\" }  }";

    JSONParser *parser = new JSONParser();

    JSONValue *jv = parser.parse(s);

    if (jv == NULL) {
        Print("error:"+(string)parser.getErrorCode()+parser.getErrorMessage());
    } else {

        Print("PARSED:"+jv.toString());

        if (jv.isObject()) { // check root value is an object. (it can be an array)

            JSONObject *jo = jv;

            // Direct access - will throw null pointer if wrong getter used.
            Print("firstName:" + jo.getString("firstName"));
            Print("city:" + jo.getObject("address").getString("city"));
            Print("phone:" + jo.getArray("phoneNumber").getObject(0).getString("number"));

            // Safe access in case JSON data is missing or different.
            if (jo.getString("firstName",s) ) Print("firstName = "+s);

            // Loop over object keys
            JSONIterator *it = new JSONIterator(jo);
            for( ; it.hasNext() ; it.next()) {
                Print("loop:"+it.key()+" = "+it.val().toString());
            }
            delete it;
        }
        delete jv;
    }
    delete parser;

The latest version can also be found here.

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?



Author: Forex Wiki Team
We are a team of highly experienced Forex Traders [2000-2023] who are dedicated to living life on our own terms. Our primary objective is to attain financial independence and freedom, and we have pursued self-education and gained extensive experience in the Forex market as our means to achieve a self-sustainable lifestyle.