Proposal for a JSON velocity tool
Last modified by JeromeVelociter on 2009/10/10 17:54
API
package org.xwiki.velocity.tools;
import net.sf.json.JSON;
import net.sf.json.JSONSerializer;
import net.sf.json.util.JSONUtils;
/**
* Velocity tool to facilitate serialization of java types and objects
* to the JSON format.
*
* @version $Id$
* @since 2.1M1
*/
public class JSONTool
{
/**
* @param object the object to transform to JSON
* @return a {@link net.sf.json.JSON} representation of the object.
*/
public JSON toJSON(Object object) {
return JSONSerializer.toJSON(object);
}
/**
* @param value the string make a JSON value String of
* @return the JSON-verified String representation of the passed String
*/
public String toValueString(String value) {
return JSONUtils.valueToString(value);
}
}
import net.sf.json.JSON;
import net.sf.json.JSONSerializer;
import net.sf.json.util.JSONUtils;
/**
* Velocity tool to facilitate serialization of java types and objects
* to the JSON format.
*
* @version $Id$
* @since 2.1M1
*/
public class JSONTool
{
/**
* @param object the object to transform to JSON
* @return a {@link net.sf.json.JSON} representation of the object.
*/
public JSON toJSON(Object object) {
return JSONSerializer.toJSON(object);
}
/**
* @param value the string make a JSON value String of
* @return the JSON-verified String representation of the passed String
*/
public String toValueString(String value) {
return JSONUtils.valueToString(value);
}
}
Test
package org.xwiki.velocity.tools;
import java.util.HashMap;
import java.util.Map;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class JSONToolTest
{
private JSONTool jsonTool;
@Before
public void initialize()
{
jsonTool = new JSONTool();
}
@Test
public void testToJSON()
{
Map<String, Object> test = new HashMap<String, Object>();
test.put("foo", "bar");
test.put("bool", Boolean.FALSE);
String jsonString = jsonTool.toJSON(test).toString();
Assert.assertEquals("{\"foo\":\"bar\",\"bool\":false}", jsonString);
}
@Test
public void testToValueString()
{
Assert.assertEquals("\"\\\"test\\\"\"", jsonTool.toValueString("\"test\""));
}
}
import java.util.HashMap;
import java.util.Map;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class JSONToolTest
{
private JSONTool jsonTool;
@Before
public void initialize()
{
jsonTool = new JSONTool();
}
@Test
public void testToJSON()
{
Map<String, Object> test = new HashMap<String, Object>();
test.put("foo", "bar");
test.put("bool", Boolean.FALSE);
String jsonString = jsonTool.toJSON(test).toString();
Assert.assertEquals("{\"foo\":\"bar\",\"bool\":false}", jsonString);
}
@Test
public void testToValueString()
{
Assert.assertEquals("\"\\\"test\\\"\"", jsonTool.toValueString("\"test\""));
}
}