在项目中,需要使用json字符串,有时候又需要将字符串转换为对象,以前写代码是直接在代码中写,方法如下:
package com.suning.review.admin.job; import java.util.ArrayList; import java.util.List; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; public class JsonTest { private static Gson gson = new GsonBuilder().enableComplexMapKeySerialization() .setDateFormat("yyyy-MM-dd HH:mm:ss").create(); public static void main(String[] args) { People p1 = new People(1, 20, "jack"); People p2 = new People(2, 21, "tom"); List<People> peoples = new ArrayList<People>(); peoples.add(p1); peoples.add(p2); String p1Str = gson.toJson(p1); // {"id":1,"age":20,"name":"jack"} String listStr = gson.toJson(peoples); // [{"id":1,"age":20,"name":"jack"},{"id":2,"age":21,"name":"tom"}] // 将字符串转换为对象 People people = gson.fromJson(p1Str, People.class); List<People> peopleList = gson.fromJson(listStr, new TypeToken<List<People>>() { }.getType()); } }
这样写当然是可以的,但是缺点是每一个需要使用到json与对象之间相互转换的类中都要声明Gson gson变量,为了代码的可重用性和设计清晰原则,可以将该json与object类转换抽取出来,独立成一个方法工具类,如下:
package util; import java.io.IOException; import java.io.UnsupportedEncodingException; import org.codehaus.jackson.JsonGenerationException; import org.codehaus.jackson.type.TypeReference; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.ObjectMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.gson.JsonParseException; /** * json转换类 */ public class JsonConvert { private static final ObjectMapper mpper = new ObjectMapper(); private static final Logger LOGGER = LoggerFactory.getLogger(JsonConvert.class); /** * json 转换为 对象 * @param json json串 * @param cl 类型 * @return * @see [相关类/方法](可选) * @since [产品/模块版本](可选) */ public static <T> T jsonToObject(String json, Class<T> cl) { LOGGER.debug("Enter method jsonToObject"); LOGGER.debug("param=" + json); try { T obj = mpper.readValue(json.getBytes("UTF-8"), cl); return obj; } catch (JsonParseException e) { LOGGER.error("JsonParseException", e); } catch (JsonMappingException e) { LOGGER.error("JsonMappingException", e); } catch (UnsupportedEncodingException e) { LOGGER.error("UnsupportedEncodingException", e); } catch (IOException e) { LOGGER.error("IOException", e); } LOGGER.debug("Exit method jsonToObject"); return null; } public static <T> T jsonToObject(String json, TypeReference<T> cl){ LOGGER.debug("Enter method jsonToObject1"); LOGGER.debug("param=" + json); try { T t = mpper.readValue(json, cl); return t; } catch (Exception e) { LOGGER.error("jsonToObject1 occur Exception", e); } LOGGER.debug("Exit method jsonToObject"); return null; } /** * 对象转换为json * @param obj 需要转换对象 * @return 转换后的json串 * @see [相关类/方法](可选) * @since [产品/模块版本](可选) */ public static String objectoJson(Object obj) { LOGGER.debug("Enter method objectoJson"); try { return mpper.writeValueAsString(obj); } catch (JsonGenerationException e) { LOGGER.error("JsonGenerationException", e); } catch (JsonMappingException e) { LOGGER.error("JsonMappingException", e); } catch (IOException e) { LOGGER.error("IOException", e); } LOGGER.debug("Exit method objectoJson"); return null; } }
如果使用该工具类,jsonTest可改变如下:
import java.util.ArrayList; import java.util.List; import org.codehaus.jackson.type.TypeReference; import com.suning.review.util.JsonConvert; public class JsonTest { public static void main(String[] args) { People p1 = new People(1, 20, "jack"); People p2 = new People(2, 21, "tom"); List<People> peoples = new ArrayList<People>(); peoples.add(p1); peoples.add(p2); String p1Str = JsonConvert.objectoJson(p1); // {"id":1,"age":20,"name":"jack"} String listStr = JsonConvert.objectoJson(peoples); // [{"id":1,"age":20,"name":"jack"},{"id":2,"age":21,"name":"tom"}] // 将字符串转换为对象 People people = JsonConvert.jsonToObject(p1Str, People.class); List<People> peopleList = JsonConvert.jsonToObject(listStr, new TypeReference<List<People>>() { }); } }
对象与字符串的相互转换就是使用反射来实现的,具体怎么实现的还得看源码啊