1 // Copyright (c) 2006-2008 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.
5 #include "content/common/json_value_serializer.h"
7 #include "base/file_util.h"
8 #include "base/json/json_reader.h"
9 #include "base/json/json_writer.h"
10 #include "base/string_util.h"
12 const char* JSONFileValueSerializer::kAccessDenied
= "Access denied.";
13 const char* JSONFileValueSerializer::kCannotReadFile
= "Can't read file.";
14 const char* JSONFileValueSerializer::kFileLocked
= "File locked.";
15 const char* JSONFileValueSerializer::kNoSuchFile
= "File doesn't exist.";
17 JSONStringValueSerializer::~JSONStringValueSerializer() {}
19 bool JSONStringValueSerializer::Serialize(const Value
& root
) {
20 if (!json_string_
|| initialized_with_const_string_
)
23 base::JSONWriter::Write(&root
, pretty_print_
, json_string_
);
27 Value
* JSONStringValueSerializer::Deserialize(int* error_code
,
28 std::string
* error_str
) {
32 return base::JSONReader::ReadAndReturnError(*json_string_
,
33 allow_trailing_comma_
,
38 /******* File Serializer *******/
40 bool JSONFileValueSerializer::Serialize(const Value
& root
) {
41 std::string json_string
;
42 JSONStringValueSerializer
serializer(&json_string
);
43 serializer
.set_pretty_print(true);
44 bool result
= serializer
.Serialize(root
);
48 int data_size
= static_cast<int>(json_string
.size());
49 if (file_util::WriteFile(json_file_path_
,
51 data_size
) != data_size
)
57 int JSONFileValueSerializer::ReadFileToString(std::string
* json_string
) {
59 if (!file_util::ReadFileToString(json_file_path_
, json_string
)) {
61 int error
= ::GetLastError();
62 if (error
== ERROR_SHARING_VIOLATION
|| error
== ERROR_LOCK_VIOLATION
) {
63 return JSON_FILE_LOCKED
;
64 } else if (error
== ERROR_ACCESS_DENIED
) {
65 return JSON_ACCESS_DENIED
;
68 if (!file_util::PathExists(json_file_path_
))
69 return JSON_NO_SUCH_FILE
;
71 return JSON_CANNOT_READ_FILE
;
76 const char* JSONFileValueSerializer::GetErrorMessageForCode(int error_code
) {
80 case JSON_ACCESS_DENIED
:
82 case JSON_CANNOT_READ_FILE
:
83 return kCannotReadFile
;
84 case JSON_FILE_LOCKED
:
86 case JSON_NO_SUCH_FILE
:
94 Value
* JSONFileValueSerializer::Deserialize(int* error_code
,
95 std::string
* error_str
) {
96 std::string json_string
;
97 int error
= ReadFileToString(&json_string
);
98 if (error
!= JSON_NO_ERROR
) {
102 *error_str
= GetErrorMessageForCode(error
);
106 JSONStringValueSerializer
serializer(json_string
);
107 return serializer
.Deserialize(error_code
, error_str
);