1// Copyright (c) 2012 The Chromium Authors. All rights reserved. 2// Use of this source code is governed by a BSD-style license that can be 3// found in the LICENSE file. 4 5#include "base/json/json_reader.h" 6 7#include "base/json/json_parser.h" 8#include "base/logging.h" 9 10namespace base { 11 12const char* JSONReader::kInvalidEscape = 13 "Invalid escape sequence."; 14const char* JSONReader::kSyntaxError = 15 "Syntax error."; 16const char* JSONReader::kUnexpectedToken = 17 "Unexpected token."; 18const char* JSONReader::kTrailingComma = 19 "Trailing comma not allowed."; 20const char* JSONReader::kTooMuchNesting = 21 "Too much nesting."; 22const char* JSONReader::kUnexpectedDataAfterRoot = 23 "Unexpected data after root element."; 24const char* JSONReader::kUnsupportedEncoding = 25 "Unsupported encoding. JSON must be UTF-8."; 26const char* JSONReader::kUnquotedDictionaryKey = 27 "Dictionary keys must be quoted."; 28 29JSONReader::JSONReader() 30 : parser_(new internal::JSONParser(JSON_PARSE_RFC)) { 31} 32 33JSONReader::JSONReader(int options) 34 : parser_(new internal::JSONParser(options)) { 35} 36 37JSONReader::~JSONReader() { 38} 39 40// static 41Value* JSONReader::Read(const StringPiece& json) { 42 internal::JSONParser parser(JSON_PARSE_RFC); 43 return parser.Parse(json); 44} 45 46// static 47Value* JSONReader::Read(const StringPiece& json, 48 int options) { 49 internal::JSONParser parser(options); 50 return parser.Parse(json); 51} 52 53// static 54Value* JSONReader::ReadAndReturnError(const StringPiece& json, 55 int options, 56 int* error_code_out, 57 std::string* error_msg_out) { 58 internal::JSONParser parser(options); 59 Value* root = parser.Parse(json); 60 if (root) 61 return root; 62 63 if (error_code_out) 64 *error_code_out = parser.error_code(); 65 if (error_msg_out) 66 *error_msg_out = parser.GetErrorMessage(); 67 68 return NULL; 69} 70 71// static 72std::string JSONReader::ErrorCodeToString(JsonParseError error_code) { 73 switch (error_code) { 74 case JSON_NO_ERROR: 75 return std::string(); 76 case JSON_INVALID_ESCAPE: 77 return kInvalidEscape; 78 case JSON_SYNTAX_ERROR: 79 return kSyntaxError; 80 case JSON_UNEXPECTED_TOKEN: 81 return kUnexpectedToken; 82 case JSON_TRAILING_COMMA: 83 return kTrailingComma; 84 case JSON_TOO_MUCH_NESTING: 85 return kTooMuchNesting; 86 case JSON_UNEXPECTED_DATA_AFTER_ROOT: 87 return kUnexpectedDataAfterRoot; 88 case JSON_UNSUPPORTED_ENCODING: 89 return kUnsupportedEncoding; 90 case JSON_UNQUOTED_DICTIONARY_KEY: 91 return kUnquotedDictionaryKey; 92 default: 93 NOTREACHED(); 94 return std::string(); 95 } 96} 97 98Value* JSONReader::ReadToValue(const std::string& json) { 99 return parser_->Parse(json); 100} 101 102JSONReader::JsonParseError JSONReader::error_code() const { 103 return parser_->error_code(); 104} 105 106std::string JSONReader::GetErrorMessage() const { 107 return parser_->GetErrorMessage(); 108} 109 110} // namespace base 111