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轉化的依賴包。
--------------------------------------分割線 --------------------------------------
Struts中異步傳送XML和JSON類型的數據 http://www.linuxidc.com/Linux/2013-08/88247.htm
Linux下JSON庫的編譯及代碼測試 http://www.linuxidc.com/Linux/2013-03/81607.htm
jQuery 獲取JSON數據[$.getJSON方法] http://www.linuxidc.com/Linux/2013-03/81673.htm
用jQuery以及JSON包將表單數據轉為JSON字符串 http://www.linuxidc.com/Linux/2013-01/77560.htm
在C語言中解析JSON配置文件 http://www.linuxidc.com/Linux/2014-05/101822.htm
--------------------------------------分割線 --------------------------------------
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();
}
}