View Javadoc

1   /*
2    * Copyright (C) 2012 Atlassian
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package com.atlassian.jira.rest.client.internal.json.gen;
18  
19  import com.atlassian.jira.rest.client.api.domain.input.ComplexIssueInputFieldValue;
20  import org.codehaus.jettison.json.JSONArray;
21  import org.codehaus.jettison.json.JSONException;
22  import org.codehaus.jettison.json.JSONObject;
23  
24  import java.util.Map;
25  
26  /**
27   * Json Generator for ComplexIssueInputFieldValue
28   *
29   * @since v1.0
30   */
31  public class ComplexIssueInputFieldValueJsonGenerator implements JsonGenerator<ComplexIssueInputFieldValue> {
32      @Override
33      public JSONObject generate(ComplexIssueInputFieldValue bean) throws JSONException {
34          final JSONObject json = new JSONObject();
35          for (Map.Entry<String, Object> entry : bean.getValuesMap().entrySet()) {
36              json.put(entry.getKey(), generateFieldValueForJson(entry.getValue()));
37          }
38          return json;
39      }
40  
41      public Object generateFieldValueForJson(Object rawValue) throws JSONException {
42          if (rawValue == null) {
43              return JSONObject.NULL;
44          } else if (rawValue instanceof ComplexIssueInputFieldValue) {
45              return generate((ComplexIssueInputFieldValue) rawValue);
46          } else if (rawValue instanceof Iterable) {
47              // array with values
48              final JSONArray array = new JSONArray();
49              for (Object value : (Iterable) rawValue) {
50                  array.put(generateFieldValueForJson(value));
51              }
52              return array;
53          } else if (rawValue instanceof CharSequence) {
54              return rawValue.toString();
55          } else if (rawValue instanceof Number) {
56              return rawValue;
57          } else {
58              throw new JSONException("Cannot generate value - unknown type for me: " + rawValue.getClass());
59          }
60      }
61  }