aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/protobuf/json/json2proto.h
blob: 5952e28c3dcf267f203d8a337653f509292ea291 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
#pragma once

#include "string_transform.h"
#include "name_generator.h"
#include "unknown_fields_collector.h"

#include <library/cpp/json/json_reader.h>
#include <library/cpp/json/json_value.h>

#include <util/generic/ptr.h>
#include <util/stream/input.h>
#include <util/stream/str.h>
#include <util/stream/mem.h>

namespace google {
    namespace protobuf {
        class Message;
    }
}

namespace NProtobufJson {
    struct TJson2ProtoConfig {
        using TSelf = TJson2ProtoConfig;
        using TValueVectorizer = std::function<NJson::TJsonValue::TArray(const NJson::TJsonValue& jsonValue)>;

        enum FldNameMode {
            FieldNameOriginalCase = 0, // default
            FieldNameLowerCase,
            FieldNameUpperCase,
            FieldNameCamelCase,
            FieldNameSnakeCase,     // ABC -> a_b_c,    UserID -> user_i_d
            FieldNameSnakeCaseDense // ABC -> abc,      UserID -> user_id
        };

        enum EnumValueMode {
            EnumCaseSensetive = 0, // default
            EnumCaseInsensetive,
            EnumSnakeCaseInsensitive
        };

        TSelf& SetFieldNameMode(FldNameMode mode) {
            Y_ENSURE(mode == FieldNameOriginalCase || !UseJsonName, "FieldNameMode and UseJsonName are mutually exclusive");
            FieldNameMode = mode;
            return *this;
        }

        TSelf& SetUseJsonName(bool jsonName) {
            Y_ENSURE(!jsonName || FieldNameMode == FieldNameOriginalCase, "FieldNameMode and UseJsonName are mutually exclusive");
            UseJsonName = jsonName;
            return *this;
        }

        TSelf& AddStringTransform(TStringTransformPtr transform) {
            StringTransforms.push_back(transform);
            return *this;
        }

        TSelf& SetCastFromString(bool cast) {
            CastFromString = cast;
            return *this;
        }

        TSelf& SetDoNotCastEmptyStrings(bool cast) {
            DoNotCastEmptyStrings = cast;
            return *this;
        }

        TSelf& SetCastRobust(bool cast) {
            CastRobust = cast;
            return *this;
        }

        TSelf& SetMapAsObject(bool mapAsObject) {
            MapAsObject = mapAsObject;
            return *this;
        }

        TSelf& SetReplaceRepeatedFields(bool replaceRepeatedFields) {
            ReplaceRepeatedFields = replaceRepeatedFields;
            return *this;
        }

        TSelf& SetNameGenerator(TNameGenerator callback) {
            NameGenerator = callback;
            return *this;
        }

        TSelf& SetEnumValueMode(EnumValueMode enumValueMode) {
            EnumValueMode = enumValueMode;
            return *this;
        }

        TSelf& SetVectorizeScalars(bool vectorizeScalars) {
            VectorizeScalars = vectorizeScalars;
            return *this;
        }

        TSelf& SetAllowComments(bool value) {
            AllowComments = value;
            return *this;
        }

        TSelf& SetAllowUnknownFields(bool value) {
            AllowUnknownFields = value;
            return *this;
        }

        TSelf& SetAllowString2TimeConversion(bool value) {
            AllowString2TimeConversion = value;
            return *this;
        }

        TSelf& SetUnknownFieldsCollector(TSimpleSharedPtr<IUnknownFieldsCollector> value) {
            UnknownFieldsCollector = std::move(value);
            return *this;
        }

        FldNameMode FieldNameMode = FieldNameOriginalCase;
        bool AllowUnknownFields = true;

        /// Use 'json_name' protobuf option for field name, mutually exclusive
        /// with FieldNameMode.
        bool UseJsonName = false;

        /// Transforms will be applied only to string values (== protobuf fields of string / bytes type).
        TVector<TStringTransformPtr> StringTransforms;

        /// Cast string json values to protobuf field type
        bool CastFromString = false;
        /// Skip empty strings, instead casting from string into scalar types.
        /// I.e. empty string like default value for scalar types.
        bool DoNotCastEmptyStrings = false;
        /// Cast all json values to protobuf field types
        bool CastRobust = false;

        /// Consider map to be an object, otherwise consider it to be an array of key/value objects
        bool MapAsObject = false;

        /// Throw exception if there is no required fields in json object.
        bool CheckRequiredFields = true;

        /// Replace repeated fields content during merging
        bool ReplaceRepeatedFields = false;

        /// Custom field names generator.
        TNameGenerator NameGenerator = {};

        /// Enum value parsing mode.
        EnumValueMode EnumValueMode = EnumCaseSensetive;

        /// Append scalars to repeated fields
        bool VectorizeScalars = false;

        /// Custom spliter non array value to repeated fields.
        TValueVectorizer ValueVectorizer;

        /// Allow js-style comments (both // and /**/)
        bool AllowComments = false;

        /// Allow nonstandard conversions, e.g. google.protobuf.Duration from String
        bool AllowString2TimeConversion = false;

        /// Stores information about unknown fields
        TSimpleSharedPtr<IUnknownFieldsCollector> UnknownFieldsCollector = nullptr;
    };

    /// @throw yexception
    void MergeJson2Proto(const NJson::TJsonValue& json, google::protobuf::Message& proto,
                    const TJson2ProtoConfig& config = TJson2ProtoConfig());

    /// @throw yexception
    void MergeJson2Proto(const TStringBuf& json, google::protobuf::Message& proto,
                    const TJson2ProtoConfig& config = TJson2ProtoConfig());

    /// @throw yexception
    inline void MergeJson2Proto(const TString& json, google::protobuf::Message& proto,
                           const TJson2ProtoConfig& config = TJson2ProtoConfig()) {
        MergeJson2Proto(TStringBuf(json), proto, config);
    }

    /// @throw yexception
    void Json2Proto(const NJson::TJsonValue& json, google::protobuf::Message& proto,
                    const TJson2ProtoConfig& config = TJson2ProtoConfig());

    /// @throw yexception
    void Json2Proto(const TStringBuf& json, google::protobuf::Message& proto,
                    const TJson2ProtoConfig& config = TJson2ProtoConfig());

    /// @throw yexception
    inline void Json2Proto(const TString& json, google::protobuf::Message& proto,
                           const TJson2ProtoConfig& config = TJson2ProtoConfig()) {
        Json2Proto(TStringBuf(json), proto, config);
    }

    /// @throw yexception
    inline void Json2Proto(IInputStream& in, google::protobuf::Message& proto,
                           const TJson2ProtoConfig& config = TJson2ProtoConfig()) {
        Json2Proto(TStringBuf(in.ReadAll()), proto, config);
    }

    /// @throw yexception
    template <typename T>
    T Json2Proto(IInputStream& in, const NJson::TJsonReaderConfig& readerConfig,
                 const TJson2ProtoConfig& config = TJson2ProtoConfig()) {
        NJson::TJsonValue jsonValue;
        NJson::ReadJsonTree(&in, &readerConfig, &jsonValue, true);
        T protoValue;
        Json2Proto(jsonValue, protoValue, config);
        return protoValue;
    }

    /// @throw yexception
    template <typename T>
    T Json2Proto(IInputStream& in, const TJson2ProtoConfig& config = TJson2ProtoConfig()) {
        // NOTE: TJson2ProtoConfig.AllowComments=true doesn't work, when using TJsonReaderConfig
        NJson::TJsonReaderConfig readerConfig;
        readerConfig.DontValidateUtf8 = true;
        return Json2Proto<T>(in, readerConfig, config);
    }

    /// @throw yexception
    template <typename T>
    T Json2Proto(const TString& value, const TJson2ProtoConfig& config = TJson2ProtoConfig()) {
        return Json2Proto<T>(TStringBuf(value), config);
    }

    /// @throw yexception
    template <typename T>
    T Json2Proto(const TStringBuf& value, const TJson2ProtoConfig& config = TJson2ProtoConfig()) {
        T protoValue;
        Json2Proto(value, protoValue, config);
        return protoValue;
    }

    /// @throw yexception
    template <typename T>
    T Json2Proto(const char* ptr, const TJson2ProtoConfig& config = TJson2ProtoConfig()) {
        return Json2Proto<T>(TStringBuf(ptr), config);
    }

}