1 // Copyright (C) 2013 Google Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 #ifndef I18N_ADDRESSINPUT_UTIL_JSON_H_ 16 #define I18N_ADDRESSINPUT_UTIL_JSON_H_ 17 18 #include <libaddressinput/util/scoped_ptr.h> 19 20 #include <string> 21 22 namespace i18n { 23 namespace addressinput { 24 25 // Parses a JSON dictionary of strings. Sample usage: 26 // scoped_ptr<Json> json(Json::Build()); 27 // std::string value; 28 // if (json->ParseObject("{'key1':'value1', 'key2':'value2'}") && 29 // json->GetStringValueForKey("key1", &value)) { 30 // Process(value); 31 // } 32 class Json { 33 public: 34 virtual ~Json(); 35 36 // Returns a new instance of |Json| object. 37 static scoped_ptr<Json> Build(); 38 39 // Parses the |json| string and returns true if |json| is valid and it is an 40 // object. 41 virtual bool ParseObject(const std::string& json) = 0; 42 43 // Sets |value| to the string for |key| if it exists and has a string value. 44 // Returns false if the key doesn't exist or doesn't correspond to a string. 45 // The JSON object must be parsed successfully in ParseObject() before 46 // invoking this method. 47 virtual bool GetStringValueForKey(const std::string& key, 48 std::string* value) const = 0; 49 50 // Sets |value| to the dictionary for |key| if it exists and has a dictionary 51 // value. Returns false if the key doesn't exist or doesn't correspond to a 52 // dictionary. The JSON object must be parsed successfully in ParseObject() 53 // before invoking this method. |value| is only guaranteed to be valid as long 54 // as |this| is valid. 55 virtual bool GetJsonValueForKey(const std::string& key, 56 scoped_ptr<Json>* value) const = 0; 57 58 protected: 59 Json(); 60 }; 61 62 } // namespace addressinput 63 } // namespace i18n 64 65 #endif // I18N_ADDRESSINPUT_UTIL_JSON_H_ 66