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.
5 #include "base/json/json_file_value_serializer.h"
7 #include "base/file_util.h"
8 #include "base/json/json_string_value_serializer.h"
9 #include "base/logging.h"
11 const char* JSONFileValueSerializer::kAccessDenied
= "Access denied.";
12 const char* JSONFileValueSerializer::kCannotReadFile
= "Can't read file.";
13 const char* JSONFileValueSerializer::kFileLocked
= "File locked.";
14 const char* JSONFileValueSerializer::kNoSuchFile
= "File doesn't exist.";
16 bool JSONFileValueSerializer::Serialize(const Value
& root
) {
17 return SerializeInternal(root
, false);
20 bool JSONFileValueSerializer::SerializeAndOmitBinaryValues(const Value
& root
) {
21 return SerializeInternal(root
, true);
24 bool JSONFileValueSerializer::SerializeInternal(const Value
& root
,
25 bool omit_binary_values
) {
26 std::string json_string
;
27 JSONStringValueSerializer
serializer(&json_string
);
28 serializer
.set_pretty_print(true);
29 bool result
= omit_binary_values
?
30 serializer
.SerializeAndOmitBinaryValues(root
) :
31 serializer
.Serialize(root
);
35 int data_size
= static_cast<int>(json_string
.size());
36 if (file_util::WriteFile(json_file_path_
,
38 data_size
) != data_size
)
44 int JSONFileValueSerializer::ReadFileToString(std::string
* json_string
) {
46 if (!file_util::ReadFileToString(json_file_path_
, json_string
)) {
48 int error
= ::GetLastError();
49 if (error
== ERROR_SHARING_VIOLATION
|| error
== ERROR_LOCK_VIOLATION
) {
50 return JSON_FILE_LOCKED
;
51 } else if (error
== ERROR_ACCESS_DENIED
) {
52 return JSON_ACCESS_DENIED
;
55 if (!file_util::PathExists(json_file_path_
))
56 return JSON_NO_SUCH_FILE
;
58 return JSON_CANNOT_READ_FILE
;
63 const char* JSONFileValueSerializer::GetErrorMessageForCode(int error_code
) {
67 case JSON_ACCESS_DENIED
:
69 case JSON_CANNOT_READ_FILE
:
70 return kCannotReadFile
;
71 case JSON_FILE_LOCKED
:
73 case JSON_NO_SUCH_FILE
:
81 Value
* JSONFileValueSerializer::Deserialize(int* error_code
,
82 std::string
* error_str
) {
83 std::string json_string
;
84 int error
= ReadFileToString(&json_string
);
85 if (error
!= JSON_NO_ERROR
) {
89 *error_str
= GetErrorMessageForCode(error
);
93 JSONStringValueSerializer
serializer(json_string
);
94 serializer
.set_allow_trailing_comma(allow_trailing_comma_
);
95 return serializer
.Deserialize(error_code
, error_str
);