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/files/file_util.h"
8 #include "base/json/json_string_value_serializer.h"
9 #include "base/logging.h"
13 const char JSONFileValueSerializer::kAccessDenied
[] = "Access denied.";
14 const char JSONFileValueSerializer::kCannotReadFile
[] = "Can't read file.";
15 const char JSONFileValueSerializer::kFileLocked
[] = "File locked.";
16 const char JSONFileValueSerializer::kNoSuchFile
[] = "File doesn't exist.";
18 JSONFileValueSerializer::JSONFileValueSerializer(
19 const base::FilePath
& json_file_path
)
20 : json_file_path_(json_file_path
),
21 allow_trailing_comma_(false),
25 JSONFileValueSerializer::~JSONFileValueSerializer() {
28 bool JSONFileValueSerializer::Serialize(const base::Value
& root
) {
29 return SerializeInternal(root
, false);
32 bool JSONFileValueSerializer::SerializeAndOmitBinaryValues(
33 const base::Value
& root
) {
34 return SerializeInternal(root
, true);
37 bool JSONFileValueSerializer::SerializeInternal(const base::Value
& root
,
38 bool omit_binary_values
) {
39 std::string json_string
;
40 JSONStringValueSerializer
serializer(&json_string
);
41 serializer
.set_pretty_print(true);
42 bool result
= omit_binary_values
?
43 serializer
.SerializeAndOmitBinaryValues(root
) :
44 serializer
.Serialize(root
);
48 int data_size
= static_cast<int>(json_string
.size());
49 if (base::WriteFile(json_file_path_
, json_string
.data(), data_size
) !=
56 int JSONFileValueSerializer::ReadFileToString(std::string
* json_string
) {
58 if (!base::ReadFileToString(json_file_path_
, json_string
)) {
60 int error
= ::GetLastError();
61 if (error
== ERROR_SHARING_VIOLATION
|| error
== ERROR_LOCK_VIOLATION
) {
62 return JSON_FILE_LOCKED
;
63 } else if (error
== ERROR_ACCESS_DENIED
) {
64 return JSON_ACCESS_DENIED
;
67 if (!base::PathExists(json_file_path_
))
68 return JSON_NO_SUCH_FILE
;
70 return JSON_CANNOT_READ_FILE
;
73 last_read_size_
= json_string
->size();
77 const char* JSONFileValueSerializer::GetErrorMessageForCode(int error_code
) {
81 case JSON_ACCESS_DENIED
:
83 case JSON_CANNOT_READ_FILE
:
84 return kCannotReadFile
;
85 case JSON_FILE_LOCKED
:
87 case JSON_NO_SUCH_FILE
:
95 base::Value
* JSONFileValueSerializer::Deserialize(int* error_code
,
96 std::string
* error_str
) {
97 std::string json_string
;
98 int error
= ReadFileToString(&json_string
);
99 if (error
!= JSON_NO_ERROR
) {
103 *error_str
= GetErrorMessageForCode(error
);
107 JSONStringValueSerializer
serializer(json_string
);
108 serializer
.set_allow_trailing_comma(allow_trailing_comma_
);
109 return serializer
.Deserialize(error_code
, error_str
);