Java中关于JSON对象类型和字符串类型之间互相转化的问题
Java中关于Json格式转化Object,Map,Collection类型和String类型之间的转化在我们实际项目中应用的很是普遍和广泛。最近工作的过程中也是经常有,因此,自己封装了一个JsonUtil.java类。
所需要的jar包:slf4j-jdk14-1.5.6.jar,slf4j-api-1.5.6.jar------>此两个jar包是slf4j日志jar包
jackson-annotations-2.1.1.jar,jackson-core-2.1.1.jar,jackson-databind-2.1.1.jar---->实现Json转化的依赖包。
--------------------------------------分割线 --------------------------------------
--------------------------------------分割线 --------------------------------------
package com.clark.util;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ser.FilterProvider;
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;
import com.clark.model.User;
/*
*
* @author caolipeng
* @title JsonUtil.java
* @description 提供用于Json数据转换的静态方法
* @version V1.0
*/
public class JsonUtil {
private static final Logger logger = LoggerFactory.getLogger(JsonUtil.class);
/**
* 性能方面 JackSon > Gson > Json 故这里决定使用JackSon 将Collection转换为Json
* 参数是Collection
*
* @param collection
*/
public static String toJson(Collection<Object> collection) {
/*
* 使用Gson的方式 Gson gson = new Gson(); String json = gson.toJson(map);
*/
/*
* 使用Jackson的方式
*/
String json = "[]";
ObjectMapper mapper = new ObjectMapper();
StringWriter sw = new StringWriter();
try {
JsonGenerator gen = new JsonFactory().createJsonGenerator(sw);
mapper.writeValue(gen, collection);
gen.close();
json = sw.toString();
} catch (JsonGenerationException e) {
json = "[]";
logger.error(
"------1------ toJson JsonGenerationException error:\n", e);
} catch (JsonMappingException e) {
json = "[]";
logger.error("------2------ toJson JsonMappingException error:\n",
e);
} catch (IOException e) {
json = "[]";
logger.error("------3------ toJson IOException error:\n", e);
}
return json;
}
/**
* @Title: toJson
* @Description: 将对象转换为Json数据
* @param @param obj
* @param @return 设定文件
* @return String 返回类型
* @throws
*/
public static String toJson(Object obj) {
String json = "[]";
ObjectMapper mapper = new ObjectMapper();
StringWriter sw = new StringWriter();
try {
JsonGenerator gen = new JsonFactory().createJsonGenerator(sw);
mapper.writeValue(gen, obj);
gen.close();
json = sw.toString();
} catch (JsonGenerationException e) {
json = "[]";
logger.error("------1------ toJson IOException error:\n", e);
} catch (JsonMappingException e) {
json = "[]";
logger.error("------2------ toJson IOException error:\n", e);
} catch (IOException e) {
json = "[]";
logger.error("------3------ toJson IOException error:\n", e);
}
return json;
}
/**
* 将MAP转为Json Map参数
*
* @param map
* @return
* @throws IOException
*/
public static String toJson(Map<String, Object> map) {
String json = "[]";
ObjectMapper mapper = new ObjectMapper();
StringWriter sw = new StringWriter();
try {
JsonGenerator gen = new JsonFactory().createJsonGenerator(sw);
mapper.writeValue(gen, map);
gen.close();
json = sw.toString();
} catch (JsonGenerationException e) {
json = "[]";
logger.error("----1------toJson JsonGenerationException:\n" + e);
} catch (JsonMappingException e) {
json = "[]";
logger.error("----2------toJson JsonMappingException:\n" + e);
} catch (IOException e) {
json = "[]";
logger.error("----3------toJson IOException:\n" + e);
}
return json;
}
/**
* 将JSON字符串 转换为对象
*
* @author weiyuanhua
* @date 2010-11-18 下午02:52:13
* @param jsonStr
* JSON字符串
* @param beanClass
* 泛型对象
* @param field
* 对象中需要忽略的属性
* @return
*/
public static Object jsonToObject(String jsonStr, Class<?> beanClass)
throws JsonParseException, JsonMappingException, IOException {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.readValue(jsonStr.getBytes(), beanClass);
}
public static Object jsonToObject(String jsonStr, String encoding,
Class<?> beanClass) throws JsonParseException,
JsonMappingException, IOException {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.readValue(jsonStr.getBytes(encoding), beanClass);
}
public static Map<String, Object> parseJSON2Map(String jsonStr)
throws JsonParseException, JsonMappingException, IOException {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.readValue(jsonStr, Map.class);
}
//不需要记性属性的忽略
public static String toJson(Object object,String filterName) {
ObjectMapper mapper = new ObjectMapper();
String json = "[]";
try {
FilterProvider filterProvider = new SimpleFilterProvider().addFilter(filterName, SimpleBeanPropertyFilter.serializeAllExcept());
json = mapper.writer(filterProvider).writeValueAsString(object);
} catch (Exception e) {
json = "[]";
logger.error("----1------toJson Exception:\n" + e);
}
return json;
}
/*
*
* @param object 需要进行json序列化的类 可以是任何复杂的类
* @param args 需要进行过滤的属性名称 类对象名称或者一些属性名称都可以进行过滤
* */
public static String toJson(Object object, String[] args, String filterName) {
String json = "[]";
ObjectMapper mapper = new ObjectMapper();
try {
FilterProvider filterProvider = new SimpleFilterProvider()
.addFilter(filterName,
SimpleBeanPropertyFilter.serializeAllExcept(args));
json = mapper.writer(filterProvider).writeValueAsString(object);
} catch (Exception e) {
json = "[]";
logger.error("----1------toJson Exception:\n" + e);
}
return json;
}
public static void main(String[] args) {
User user = new User(12, "aaa", "123456", new Date());
// String result = toJson(user, "id");
String result = toJson(user);
System.out.println(result);
List list = new ArrayList();
list.add(0,"name");
list.add(1,"favorite");
String li = toJson(list);
System.out.println(li);
Map<String,String> map = new HashMap<String,String>();
map.put("password", "123");
map.put("name", "clark");
map.put("call", "wowo");
String mr = toJson(map);
System.out.println(mr);
Date d = new Date();
String jsonStr = "{\"id\":23,\"name\":\"44444\"}";
try {
User u = (User)jsonToObject(jsonStr, User.class);
System.out.println(u.getName());
Map<String, Object> mapResult = parseJSON2Map(jsonStr);
Set<String> key = mapResult.keySet();
Iterator iter = key.iterator();
while(iter.hasNext()){
String k = (String) iter.next();
System.out.println(mapResult.get(k));
}
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
在应用测试中的Model类---User.java类如下:
package com.clark.model;
import java.util.Date;
public class User {
private int id;
private String name;
private String password;
private Date date;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public User(int id, String name, String password, Date date) {
super();
this.id = id;
this.name = name;
this.password = password;
this.date = date;
}
public User(){
}
@Override
public String toString() {
return "Id:"+this.getId()+"\n"+"name:"+this.getName()+"\n"+"password:"+this.getPassword();
}
}