1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.neo4j.server.rest.domain;
21
22 import org.codehaus.jackson.JsonGenerator;
23 import org.codehaus.jackson.map.ObjectMapper;
24 import org.neo4j.server.rest.web.PropertyValueException;
25
26 import java.io.IOException;
27 import java.io.StringWriter;
28 import java.util.Collection;
29 import java.util.List;
30 import java.util.Map;
31
32 public class JsonHelper {
33
34 static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
35
36 @SuppressWarnings("unchecked")
37 public static Map<String, Object> jsonToMap(String json) throws JsonParseException
38 {
39 return (Map<String, Object>) readJson( json );
40 }
41
42 @SuppressWarnings("unchecked")
43 public static List<Map<String, Object>> jsonToList( String json ) throws JsonParseException
44 {
45 return (List<Map<String, Object>>) readJson( json );
46 }
47
48 private static Object readJson( String json ) throws JsonParseException
49 {
50 ObjectMapper mapper = new ObjectMapper();
51 try {
52 return mapper.readValue(json, Object.class);
53 } catch (IOException e) {
54 throw new JsonParseException( e );
55 }
56 }
57
58 public static Object jsonToSingleValue(String json) throws org.neo4j.server.rest.web.PropertyValueException
59 {
60 Object jsonObject = readJson( json );
61 return jsonObject instanceof Collection<?> ? jsonObject
62 : assertSupportedPropertyValue( jsonObject );
63 }
64
65 private static Object assertSupportedPropertyValue( Object jsonObject )
66 throws PropertyValueException
67 {
68 if ( jsonObject == null )
69 {
70 throw new org.neo4j.server.rest.web.PropertyValueException( "null value not supported" );
71
72 }
73
74 if ( jsonObject instanceof String )
75 {
76 }
77 else if ( jsonObject instanceof Number )
78 {
79 }
80 else if ( jsonObject instanceof Boolean )
81 {
82 }
83 else
84 {
85 throw new org.neo4j.server.rest.web.PropertyValueException(
86 "Unsupported value type "
87 + jsonObject.getClass()
88 + "."
89 + " Supported value types are all java primitives (byte, char, short, int, "
90 + "long, float, double) and String, as well as arrays of all those types" );
91 }
92 return jsonObject;
93 }
94
95 public static String createJsonFrom(Object data) throws JsonBuildRuntimeException
96 {
97 try {
98 StringWriter writer = new StringWriter();
99 JsonGenerator generator = OBJECT_MAPPER.getJsonFactory()
100 .createJsonGenerator( writer ).useDefaultPrettyPrinter();
101 OBJECT_MAPPER.writeValue( generator, data );
102 writer.close();
103 return writer.getBuffer().toString();
104 } catch (IOException e) {
105 throw new JsonBuildRuntimeException( e );
106 }
107 }
108 }