e3f55a0e696bc01e166f0638ba8672f681a6c16d
[so.git] / adapters / mso-adapters-rest-interface / src / main / java / org / openecomp / mso / adapters / json / MapSerializer.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * OPENECOMP - MSO
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20 package org.openecomp.mso.adapters.json;
21
22 import org.codehaus.jackson.JsonGenerationException;
23 import org.codehaus.jackson.JsonGenerator;
24 import org.codehaus.jackson.map.JsonSerializer;
25 import org.codehaus.jackson.map.SerializerProvider;
26
27 import java.io.IOException;
28 import java.util.Map;
29
30 /**
31  * Custom JSON Serializer for Map<String, String>.
32  * In MSO with Jackson 1.9.12 and RestEasy 3.0.8, maps in JSON are serialized as
33  * follows:
34  * <pre>
35  * "params": {
36  *   "entry": [
37  *     {"key": "P1", "value": "V1"},
38  *     {"key": "P2", "value": "V2"},
39  *     ...
40  *     {"key": "PN", "value": "VN"}
41  *   ]
42  * }
43  * </pre>
44  * The implementation uses a TreeMap, so entries are always sorted according
45  * to the natural ordering of the keys.
46  */
47 public class MapSerializer extends JsonSerializer<Map<String, String>> {
48         @Override
49         public void serialize(Map<String, String> map, JsonGenerator jsonGenerator,
50                         SerializerProvider serializerProvider) throws IOException,
51                         JsonGenerationException {
52
53                 jsonGenerator.writeStartObject();
54                 jsonGenerator.writeArrayFieldStart("entry");
55
56                 for (String key : map.keySet()) {
57                         String value = map.get(key);
58                         jsonGenerator.writeStartObject();
59                         jsonGenerator.writeStringField("key", key);
60                         jsonGenerator.writeStringField("value", value);
61                         jsonGenerator.writeEndObject();
62                 }
63
64                 jsonGenerator.writeEndArray();
65                 jsonGenerator.writeEndObject();
66         }
67 }