首先弄个工具类:
public class JacksonUtil {
public static ObjectMapper objectMapper;
/**
* 使用泛型方法,把json字符串转换为相应的JavaBean对象。
* (1)转换为普通JavaBean:readValue(json,Student.class)
* (2)转换为List,如List<Student>,将第二个参数传递为Student
* [].class.然后使用Arrays.asList();方法把得到的数组转换为特定类型的List
*
* @param jsonStr
* @param valueType
* @return
*/
public static <T> T readValue(String jsonStr, Class<T> valueType) {
if (objectMapper == null) {
objectMapper = new ObjectMapper();
}
try {
return objectMapper.readValue(jsonStr, valueType);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* json数组转List
* @param jsonStr
* @param valueTypeRef
* @return
*/
public static <T> T readValue(String jsonStr, TypeReference<T> valueTypeRef){
if (objectMapper == null) {
objectMapper = new ObjectMapper();
}
try {
return objectMapper.readValue(jsonStr, valueTypeRef);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 把JavaBean转换为json字符串
*
* @param object
* @return
*/
public static String toJSon(Object object) {
if (objectMapper == null) {
objectMapper = new ObjectMapper();
}
try {
return objectMapper.writeValueAsString(object);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
后台弄个对象或集合:
ObjectMapper mapper = CommonUtil.getMapperInstance(false);
Option option1=new Option();
option1.setId(“1-1”);
option1.setTitle(“动感地带”);
Option option2=new Option();
option2.setId(“1-2”);
option2.setTitle(“神州行”);
Option option3=new Option();
option3.setId(“1-3”);
option3.setTitle(“全球通”);
List<Option> optionList1=new ArrayList<Option>();
optionList1.add(option1);
optionList1.add(option2);
optionList1.add(option3);
Topic topic1=new Topic();
topic1.setId(“1”);
topic1.setTitle(“【第一题:请问您使用目前中国移动的哪种品牌?】”);
topic1.setOptionList(optionList1);
Option option4=new Option();
option4.setId(“2-1”);
option4.setTitle(“很差”);
Option option5=new Option();
option5.setId(“2-2”);
option5.setTitle(“差”);
Option option6=new Option();
option6.setId(“2-3”);
option6.setTitle(“好”);
List<Option> optionList2=new ArrayList<Option>();
optionList2.add(option4);
optionList2.add(option5);
optionList2.add(option6);
Topic topic2=new Topic();
topic2.setId(“2”);
topic2.setTitle(“【第二题:您觉得中国移动服务营业厅的整体环境怎么样?】”);
topic2.setOptionList(optionList2);
List<Topic> topicList=new ArrayList<Topic>();
topicList.add(topic1);
topicList.add(topic2);
Template template=new Template();
template.setId(“1”);
template.setTitle(“10086满意度调查”);
template.setTopicList(topicList);
System.out.println(“将模板实体转换为JSON=”+JacksonUtil.toJSon(template));
System.out.println(“将集合转换为JSON=”+JacksonUtil.toJSon(topicList));
CommonUtil
private static ObjectMapper mapper;
/**
*
*
* @param createNew
* 是否创建一个新的Mapper
* @return
*/
public static synchronized ObjectMapper getMapperInstance(boolean createNew) {
if (createNew) {
return new ObjectMapper();
} else if (mapper == null) {
mapper = new ObjectMapper();
}
return mapper;
}