1. Project Clover database Tue Dec 20 2016 21:24:09 CET
  2. Package org.xwiki.velocity.tools

File JSONTool.java

 

Coverage histogram

../../../../img/srcFileCovDistChart9.png
38% of files have more coverage

Code metrics

0
15
4
3
125
63
6
0.4
3.75
1.33
1.5

Classes

Class Line # Actions
JSONTool 48 13 0% 4 2
0.866666786.7%
JSONTool.JSONObjectSerializer 106 1 0% 1 0
1.0100%
JSONTool.JSONArraySerializer 116 1 0% 1 0
1.0100%
 

Contributing tests

This file is covered by 18 tests. .

Source view

1    /*
2    * See the NOTICE file distributed with this work for additional
3    * information regarding copyright ownership.
4    *
5    * This is free software; you can redistribute it and/or modify it
6    * under the terms of the GNU Lesser General Public License as
7    * published by the Free Software Foundation; either version 2.1 of
8    * the License, or (at your option) any later version.
9    *
10    * This software is distributed in the hope that it will be useful,
11    * but WITHOUT ANY WARRANTY; without even the implied warranty of
12    * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13    * Lesser General Public License for more details.
14    *
15    * You should have received a copy of the GNU Lesser General Public
16    * License along with this software; if not, write to the Free
17    * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
18    * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
19    */
20    package org.xwiki.velocity.tools;
21   
22    import java.io.IOException;
23   
24    import org.apache.commons.lang3.StringUtils;
25    import org.json.JSONArray;
26    import org.json.JSONObject;
27    import org.slf4j.Logger;
28    import org.slf4j.LoggerFactory;
29   
30    import com.fasterxml.jackson.core.JsonGenerator;
31    import com.fasterxml.jackson.core.JsonProcessingException;
32    import com.fasterxml.jackson.core.Version;
33    import com.fasterxml.jackson.databind.JsonSerializer;
34    import com.fasterxml.jackson.databind.ObjectMapper;
35    import com.fasterxml.jackson.databind.SerializerProvider;
36    import com.fasterxml.jackson.databind.module.SimpleModule;
37   
38    import net.sf.json.JSON;
39    import net.sf.json.JSONException;
40    import net.sf.json.JSONSerializer;
41   
42    /**
43    * Velocity tool to facilitate serialization of Java objects to the JSON format.
44    *
45    * @version $Id: 55c758baf354ea5bbb25c11382398c9680f9b531 $
46    * @since 4.0M2
47    */
 
48    public class JSONTool
49    {
50    /** Logging helper object. */
51    private Logger logger = LoggerFactory.getLogger(JSONTool.class);
52   
53    /**
54    * Serialize a Java object to the JSON format.
55    * <p>
56    * Examples:
57    * <ul>
58    * <li>numbers and boolean values: 23, 13.5, true, false</li>
59    * <li>strings: "one\"two'three" (quotes included)</li>
60    * <li>arrays and collections: [1, 2, 3]</li>
61    * <li>maps: {"number": 23, "boolean": false, "string": "value"}</li>
62    * <li>beans: {"enabled": true, "name": "XWiki"} for a bean that has #isEnabled() and #getName() getters</li>
63    * </ul>
64    *
65    * @param object the object to be serialized to the JSON format
66    * @return the JSON-verified string representation of the given object
67    */
 
68  643 toggle public String serialize(Object object)
69    {
70  643 try {
71  643 ObjectMapper mapper = new ObjectMapper();
72  643 SimpleModule m = new SimpleModule("org.json.* serializer", new Version(1, 0, 0, "", "org.json", "json"));
73  643 m.addSerializer(JSONObject.class, new JSONObjectSerializer());
74  643 m.addSerializer(JSONArray.class, new JSONArraySerializer());
75  643 mapper.registerModule(m);
76  643 return mapper.writeValueAsString(object);
77    } catch (JsonProcessingException e) {
78  0 this.logger.error("Failed to serialize object to JSON", e);
79    }
80   
81  0 return null;
82    }
83   
84    /**
85    * Parse a serialized JSON into a real JSON object. Only valid JSON strings can be parsed, and doesn't support
86    * JSONP. If the argument is not valid JSON, then {@code null} is returned.
87    *
88    * @param json the string to parse, must be valid JSON
89    * @return the parsed JSON, either a {@link net.sf.json.JSONObject} or a {@link net.sf.json.JSONArray}, or
90    * {@code null} if the argument is not a valid JSON
91    * @since 5.2M1
92    */
93    // FIXME: directly returning in a public API the object of a dead library, not very nice for something introduced in
94    // 5.2...
 
95  11 toggle public JSON parse(String json)
96    {
97  11 try {
98  11 return JSONSerializer.toJSON(json);
99    } catch (JSONException ex) {
100  2 this.logger.info("Tried to parse invalid JSON: [{}], exception was: {}", StringUtils.abbreviate(json, 32),
101    ex.getMessage());
102  2 return null;
103    }
104    }
105   
 
106    class JSONObjectSerializer extends JsonSerializer<JSONObject>
107    {
 
108  2 toggle @Override
109    public void serialize(JSONObject value, JsonGenerator jgen, SerializerProvider provider)
110    throws IOException, JsonProcessingException
111    {
112  2 jgen.writeRawValue(value.toString());
113    }
114    }
115   
 
116    class JSONArraySerializer extends JsonSerializer<JSONArray>
117    {
 
118  2 toggle @Override
119    public void serialize(JSONArray value, JsonGenerator jgen, SerializerProvider provider)
120    throws IOException, JsonProcessingException
121    {
122  2 jgen.writeRawValue(value.toString());
123    }
124    }
125    }