Commit d40cb5fc authored by Paul Asmuth's avatar Paul Asmuth
Browse files

HashMap<String,String> to/from JSON

parent d794a4da
Loading
Loading
Loading
Loading
+40 −0
Original line number Diff line number Diff line
@@ -241,6 +241,46 @@ JSONObject fromJSONImpl(
  return JSONObject(begin, begin + begin->size);
}

template <>
HashMap<String, String> fromJSONImpl(
    std::vector<JSONToken>::const_iterator begin,
    std::vector<JSONToken>::const_iterator end) {
  HashMap<String, String> map;

  if (begin == end || begin + begin->size > end) {
    RAISE(kIndexError);
  }

  if (begin->type != json::JSON_OBJECT_BEGIN) {
    RAISEF(kParseError, "expected JSON_OBJECT_BEGIN, got: $0", begin->type);
  }

  for (++begin; begin != end;) {
    String key;

    switch (begin->type) {
      case json::JSON_STRING:
        key = begin->data;
        ++begin;

      default:
        RAISEF(kParseError, "expected JSON_STRING, got: $0", begin->type);
    }

    switch (begin->type) {
      case json::JSON_STRING:
        map[key] = begin->data;
        ++begin;

      default:
        RAISEF(kParseError, "expected JSON_STRING, got: $0", begin->type);
    }
  }

  return map;
}


} // namespace json

template <>
+12 −0
Original line number Diff line number Diff line
@@ -255,6 +255,18 @@ void toJSONImpl(const JSONObject& obj, O* target) {
  }
}

template <typename O>
void toJSONImpl(const HashMap<String, String>& val, O* target) {
  target->emplace_back(json::JSON_OBJECT_BEGIN);

  for (const auto& pair : val) {
    target->emplace_back(json::JSON_STRING, pair.first);
    target->emplace_back(json::JSON_STRING, pair.second);
  }

  target->emplace_back(json::JSON_OBJECT_END);
}

}
}
#endif