好的,问题出来了,我们如何解决呢?使其通过实验,Jackson JSON其实在默认设置下已经具备了对Unicode编码的JSON数据进行解析。所欠缺的就是在序列化对象时缺少相应的步骤。好在Jackson JSON框架允许我们自定义序列化方法。那么我们就来写一个序列化类:
package net.csdn.blog.chaijunkun.util; import java.io.IOException; import org.codehaus.jackson.JsonGenerationException; import org.codehaus.jackson.JsonGenerator; import org.codehaus.jackson.JsonProcessingException; import org.codehaus.jackson.impl.JsonWriteContext; import org.codehaus.jackson.map.JsonSerializer; import org.codehaus.jackson.map.SerializerProvider; import org.codehaus.jackson.util.CharTypes; public class StringUnicodeSerializer extends JsonSerializer<String> { private final char[] HEX_CHARS = "0123456789ABCDEF".toCharArray(); private final int[] ESCAPE_CODES = CharTypes.get7BitOutputEscapes(); private void writeUnicodeEscape(JsonGenerator gen, char c) throws IOException { gen.writeRaw('\\'); gen.writeRaw('u'); gen.writeRaw(HEX_CHARS[(c >> 12) & 0xF]); gen.writeRaw(HEX_CHARS[(c >> 8) & 0xF]); gen.writeRaw(HEX_CHARS[(c >> 4) & 0xF]); gen.writeRaw(HEX_CHARS[c & 0xF]); } private void writeShortEscape(JsonGenerator gen, char c) throws IOException { gen.writeRaw('\\'); gen.writeRaw(c); } @Override public void serialize(String str, JsonGenerator gen, SerializerProvider provider) throws IOException, JsonProcessingException { int status = ((JsonWriteContext) gen.getOutputContext()).writeValue(); switch (status) { case JsonWriteContext.STATUS_OK_AFTER_COLON: gen.writeRaw(':'); break; case JsonWriteContext.STATUS_OK_AFTER_COMMA: gen.writeRaw(','); break; case JsonWriteContext.STATUS_EXPECT_NAME: throw new JsonGenerationException("Can not write string value here"); } gen.writeRaw('"');//写入JSON中字符串的开头引号 for (char c : str.toCharArray()) { if (c >= 0x80){ writeUnicodeEscape(gen, c); // 为所有非ASCII字符生成转义的unicode字符 }else { // 为ASCII字符中前128个字符使用转义的unicode字符 int code = (c < ESCAPE_CODES.length ? ESCAPE_CODES[c] : 0); if (code == 0){ gen.writeRaw(c); // 此处不用转义 }else if (code < 0){ writeUnicodeEscape(gen, (char) (-code - 1)); // 通用转义字符 }else { writeShortEscape(gen, (char) code); // 短转义字符 (\n \t ...) } } } gen.writeRaw('"');//写入JSON中字符串的结束引号 } }
if (objectMapper== null){ objectMapper= new ObjectMapper(); //当找不到对应的序列化器时 忽略此字段 objectMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false); //使Jackson JSON支持Unicode编码非ASCII字符 CustomSerializerFactory serializerFactory= new CustomSerializerFactory(); serializerFactory.addSpecificMapping(String.class, new StringUnicodeSerializer()); objectMapper.setSerializerFactory(serializerFactory); //支持结束 }
2014年5月13日补充:最近被问到很多次关于单例模式的实现。上面的写法真的很不安全,没有加锁,也没有对objectMapper进行volatile修饰(即所谓的“双检索”货“双重检查”),因此最简单的可靠的方法应该使用“枚举单例法”。
2014年11月21日补充:由于Jackson 2的版本变化,CustomSerializerFactory已经被去掉了,经过实验,可以使用这种方式代替:
if (objectMapper== null){ objectMapper= new ObjectMapper(); //当找不到对应的序列化器时 忽略此字段 objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); //使Jackson JSON支持Unicode编码非ASCII字符 SimpleModule module = new SimpleModule(); module.addSerializer(String.class, new StringUnicodeSerializer()); objectMapper.registerModule(module); //设置null值不参与序列化(字段不被显示) objectMapper.setSerializationInclusion(Include.NON_NULL); //支持结束 }
接下来我们来做一个测试用的对象,验证我们的代码:
package net.csdn.blog.chaijunkun.json; import java.util.Date; import net.csdn.blog.chaijunkun.util.DateDeserializer; import net.csdn.blog.chaijunkun.util.DateSerializer; import net.csdn.blog.chaijunkun.util.DateTimeDeserializer; import net.csdn.blog.chaijunkun.util.DateTimeSerializer; import org.codehaus.jackson.annotate.JsonPropertyOrder; import org.codehaus.jackson.map.annotate.JsonDeserialize; import org.codehaus.jackson.map.annotate.JsonSerialize; @JsonPropertyOrder(alphabetic= false) public class DemoObj { private Integer sid; private String stuName; private Boolean sex; @JsonSerialize(using= DateSerializer.class) @JsonDeserialize(using= DateDeserializer.class) private Date birthday; @JsonSerialize(using= DateTimeSerializer.class) @JsonDeserialize(using= DateTimeDeserializer.class) private Date logTime; //Getters and Setters }
package net.csdn.blog.chaijunkun.test; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import net.csdn.blog.chaijunkun.json.DemoObj; import net.csdn.blog.chaijunkun.util.JSONUtil; import org.apache.log4j.Logger; public class JSONTest { private static Logger logger= Logger.getLogger(JSONTest.class); private static String json= "{\"sid\":2,\"stuName\":\"\u6C5F\u5357Style\",\"sex\":true,\"birthday\":\"2012-07-15\",\"logTime\":\"2012-12-04 19:22:36\"}"; public static void main(String[] args) { DemoObj objSrc= new DemoObj(); objSrc.setSid(1); objSrc.setStuName("鸟叔"); objSrc.setSex(true); Calendar calendar= Calendar.getInstance(); calendar.set(1977, Calendar.DECEMBER, 31, 0, 0, 0); objSrc.setBirthday(calendar.getTime()); objSrc.setLogTime(new Date()); logger.info(String.format("转换为JSON后的数据:%s", JSONUtil.toJSON(objSrc))); DemoObj objDes= JSONUtil.fromJSON(json, DemoObj.class); if(objDes==null){ logger.info("反序列化失败"); }else{ logger.info("反序列化成功"); SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); logger.info(String.format("标识:%d", objDes.getSid())); logger.info(String.format("姓名:%s", objDes.getStuName())); logger.info(String.format("性别:%s", objDes.getSex()==true?"男":"女")); logger.info(String.format("生日:%s", sdf.format(objDes.getBirthday()))); logger.info(String.format("登录日期:%s", sdf.format(objDes.getLogTime()))); } } }
看一下输出:
转换为JSON后的数据:{"sid":1,"stuName":"\u9E1F\u53D4","sex":true,"birthday":"1977-12-31","logTime":"2012-12-04 19:31:57"} 反序列化成功 标识:2 姓名:江南Style 性别:男 生日:2012-07-15 00:00:00 登录日期:2012-12-04 19:22:36
细心的朋友也许观察到了,在测试用的对象定义代码中,针对同样Date类型的属性“birthday”和“logTime”,我们指定了不同的序列化与反序列化方法。让我们来看烂这两个有什么不同:
package net.csdn.blog.chaijunkun.util; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import org.codehaus.jackson.JsonGenerator; import org.codehaus.jackson.JsonProcessingException; import org.codehaus.jackson.map.JsonSerializer; import org.codehaus.jackson.map.SerializerProvider; public class DateTimeSerializer extends JsonSerializer<Date> { @Override public void serialize(Date date, JsonGenerator gen, SerializerProvider provider) throws IOException, JsonProcessingException { SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String formattedDate= sdf.format(date); gen.writeString(formattedDate); } }
package net.csdn.blog.chaijunkun.util; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import org.codehaus.jackson.JsonParser; import org.codehaus.jackson.JsonProcessingException; import org.codehaus.jackson.map.DeserializationContext; import org.codehaus.jackson.map.JsonDeserializer; public class DateTimeDeserializer extends JsonDeserializer<Date> { @Override public Date deserialize(JsonParser parser, DeserializationContext context) throws IOException, JsonProcessingException { String dateFormat= "yyyy-MM-dd HH:mm:ss"; SimpleDateFormat sdf= new SimpleDateFormat(dateFormat); try{ String fieldData= parser.getText(); return sdf.parse(fieldData); }catch (Exception e) { Calendar ca= Calendar.getInstance(); ca.set(1970, Calendar.JANUARY, 1, 0, 0, 0); return ca.getTime(); } } }
package net.csdn.blog.chaijunkun.util; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import org.codehaus.jackson.JsonGenerator; import org.codehaus.jackson.JsonProcessingException; import org.codehaus.jackson.map.JsonSerializer; import org.codehaus.jackson.map.SerializerProvider; public class DateSerializer extends JsonSerializer<Date> { @Override public void serialize(Date date, JsonGenerator gen, SerializerProvider provider) throws IOException, JsonProcessingException { SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); String formattedDate= sdf.format(date); gen.writeString(formattedDate); } }
package net.csdn.blog.chaijunkun.util; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import org.codehaus.jackson.JsonParser; import org.codehaus.jackson.JsonProcessingException; import org.codehaus.jackson.map.DeserializationContext; import org.codehaus.jackson.map.JsonDeserializer; public class DateDeserializer extends JsonDeserializer<Date> { @Override public Date deserialize(JsonParser parser, DeserializationContext context) throws IOException, JsonProcessingException { String dateFormat= "yyyy-MM-dd"; SimpleDateFormat sdf= new SimpleDateFormat(dateFormat); try{ String fieldData= parser.getText(); return sdf.parse(fieldData); }catch (Exception e) { Calendar ca= Calendar.getInstance(); ca.set(1970, Calendar.JANUARY, 1, 0, 0, 0); return ca.getTime(); } } }
2012年12月17日补充:
最近有一个需求,需要在序列化与反序列化对象的时候对数据进行修改,当发现数据源值为空时需要让生成的JSON显示改字段为“游客”。可是我无论如何指定序列化器与反序列化器都无效。程序根本走不到指定的代码中去。后来我得出结论,Jackson JSON在反序列化对象的时候,若JSON数据中对应属性为null,则不会走自定义的反序列化器;同样地,当你设置对象的某个属性值为null时,在将其序列化成JSON时,也不会走自定义的序列化器。因此若有类似的需求,请在序列化与反序列化之前通过硬代码形式判断和修改,千万不要什么事都指望着序列化器与反序列化器。
参考资料:来源于国外网站的一篇介绍如何转码的文章,原文有点错误。我将其改正了,并加入了一些中文注释:http://wiki.fasterxml.com/JacksonSampleQuoteChars