summaryrefslogtreecommitdiff
path: root/cdec_json_parser/json_parse.h
blob: 80c037b7ae0ddb2dab647249e1f3158fe9c64f72 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#ifndef _JSON_WRAPPER_H_
#define _JSON_WRAPPER_H_

#include <iostream>
#include <cassert>
#include "JSON_parser.h"

class JSONParser {
 public:
  JSONParser() {
    state = -1;
    init_JSON_config(&config);
    hack.mf = &JSONParser::Callback;
    config.depth = 10;
    config.callback_ctx = reinterpret_cast<void*>(this);
    config.callback = hack.cb;
    config.allow_comments = 1;
    config.handle_floats_manually = 1;
    jc = new_JSON_parser(&config);
  }
  virtual ~JSONParser() {
    delete_JSON_parser(jc);
  }
  bool Parse(std::istream* in) {
    int count = 0;
    int lc = 1;
    for (; in ; ++count) {
      int next_char = in->get();
      if (!in->good()) break;
      if (lc == '\n') { ++lc; }
      if (!JSON_parser_char(jc, next_char)) {
        std::cerr << "JSON_parser_char: syntax error, line " << lc << " (byte " << count << ")" << std::endl;
        return false;
      }
    }
    if (!JSON_parser_done(jc)) {
      std::cerr << "JSON_parser_done: syntax error\n";
      return false;
    }
    return true;
  }
  static void WriteEscapedString(const std::string& in, std::ostream* out);
 protected:
  bool HandleJSONEvent(int type, const JSON_value* value);
 private:
  int state;
  std::string cur_key;
  std::string cat;
  int Callback(int type, const JSON_value* value) {
    if (HandleJSONEvent(type, value)) return 1;
    return 0;
  }
  JSON_parser_struct* jc;
  JSON_config config;
  typedef int (JSONParser::* MF)(int type, const struct JSON_value_struct* value);
  union CBHack {
    JSON_parser_callback cb;
    MF mf;
  } hack;
};

#endif