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.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  		}
45  		else if (rawValue instanceof ComplexIssueInputFieldValue) {
46  			return generate((ComplexIssueInputFieldValue) rawValue);
47  		} else if (rawValue instanceof Iterable) {
48  			// array with values
49  			final JSONArray array = new JSONArray();
50  			for (Object value : (Iterable) rawValue) {
51  				array.put(generateFieldValueForJson(value));
52  			}
53  			return array;
54  		} else if (rawValue instanceof CharSequence) {
55  			return rawValue.toString();
56  		} else if (rawValue instanceof Number) {
57  			return rawValue;
58  		} else {
59  			throw new JSONException("Cannot generate value - unknown type for me: " + rawValue.getClass());
60  		}
61  	}
62  }