1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package com.atlassian.jira.rest.client.internal.json;
18
19 import com.atlassian.jira.rest.client.api.domain.BasicUser;
20 import com.atlassian.jira.rest.client.api.domain.IssueField;
21 import org.codehaus.jettison.json.JSONException;
22 import org.codehaus.jettison.json.JSONObject;
23
24 import java.util.HashMap;
25 import java.util.Map;
26
27 public class IssueFieldJsonParser {
28 private static final String VALUE_ATTRIBUTE = "value";
29
30 private Map<String, JsonObjectParser> registeredValueParsers = new HashMap<String, JsonObjectParser>() {{
31 put("com.atlassian.jira.plugin.system.customfieldtypes:float", new FloatingPointFieldValueParser());
32 put("com.atlassian.jira.plugin.system.customfieldtypes:userpicker", new FieldValueJsonParser<BasicUser>(new BasicUserJsonParser()));
33 put("java.lang.String", new StringFieldValueParser());
34 }};
35
36 @SuppressWarnings("unchecked")
37 public IssueField parse(JSONObject jsonObject, String id) throws JSONException {
38 String type = jsonObject.getString("type");
39 final String name = jsonObject.getString("name");
40 final Object valueObject = jsonObject.opt(VALUE_ATTRIBUTE);
41 final Object value;
42
43 if ("comment".equals(name)) {
44 type = "com.atlassian.jira.Comment";
45 }
46
47 if (valueObject == null) {
48 value = null;
49 } else {
50 final JsonObjectParser valueParser = registeredValueParsers.get(type);
51 if (valueParser != null) {
52 value = valueParser.parse(jsonObject);
53 } else {
54 value = valueObject.toString();
55 }
56 }
57 return new IssueField(id, name, type, value);
58 }
59
60 static class FieldValueJsonParser<T> implements JsonObjectParser<T> {
61 private final JsonObjectParser<T> jsonParser;
62
63 public FieldValueJsonParser(JsonObjectParser<T> jsonParser) {
64 this.jsonParser = jsonParser;
65 }
66
67 @Override
68 public T parse(JSONObject json) throws JSONException {
69 final JSONObject valueObject = json.optJSONObject(VALUE_ATTRIBUTE);
70 if (valueObject == null) {
71 throw new JSONException("Expected JSONObject with [" + VALUE_ATTRIBUTE + "] attribute present.");
72 }
73 return jsonParser.parse(valueObject);
74 }
75 }
76
77
78 static class FloatingPointFieldValueParser implements JsonObjectParser<Double> {
79
80 @Override
81 public Double parse(JSONObject jsonObject) throws JSONException {
82 final String s = JsonParseUtil.getNullableString(jsonObject, VALUE_ATTRIBUTE);
83 if (s == null) {
84 return null;
85 }
86 try {
87 return Double.parseDouble(s);
88 } catch (NumberFormatException e) {
89 throw new JSONException("[" + s + "] is not a valid floating point number");
90 }
91 }
92 }
93
94 static class StringFieldValueParser implements JsonObjectParser<String> {
95
96 @Override
97 public String parse(JSONObject jsonObject) throws JSONException {
98 return JsonParseUtil.getNullableString(jsonObject, VALUE_ATTRIBUTE);
99 }
100 }
101
102
103 }