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.domain.BasicUser;
20 import com.atlassian.jira.rest.client.domain.Field;
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 JsonFieldParser {
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 public Field parse(JSONObject jsonObject, String id) throws JSONException {
37 String type = jsonObject.getString("type");
38 final String name = jsonObject.getString("name");
39 final Object valueObject = jsonObject.opt(VALUE_ATTRIBUTE);
40 final Object value;
41
42 if ("comment".equals(name)) {
43 type = "com.atlassian.jira.Comment";
44 }
45
46 if (valueObject == null) {
47 value = null;
48 } else {
49 final JsonObjectParser valueParser = registeredValueParsers.get(type);
50 if (valueParser != null) {
51 value = valueParser.parse(jsonObject);
52 } else {
53 value = valueObject.toString();
54 }
55 }
56 return new Field(id, name, type, value);
57 }
58
59 static class FieldValueJsonParser<T> implements JsonObjectParser<T> {
60 private final JsonObjectParser<T> jsonParser;
61
62 public FieldValueJsonParser(JsonObjectParser<T> jsonParser) {
63 this.jsonParser = jsonParser;
64 }
65
66 @Override
67 public T parse(JSONObject json) throws JSONException {
68 final JSONObject valueObject = json.optJSONObject(VALUE_ATTRIBUTE);
69 if (valueObject == null) {
70 throw new JSONException("Expected JSONObject with [" + VALUE_ATTRIBUTE + "] attribute present.");
71 }
72 return jsonParser.parse(valueObject);
73 }
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
104 }