Gson 라이브러리 기반 json/bean 분석 도구
package zmx.gson.test;
import java.io.Serializable;
import java.util.Date;
public class UserInfo implements Serializable{
private static final long serialVersionUID = -7371753338546349542L;
private String id;
private String username;
private String face;
private Date birthday;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getFace() {
return face;
}
public void setFace(String face) {
this.face = face;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
}
package zmx.gson.test;
import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
/**
*
* @author zhangwenchao
*
*/
public class GsonUtil {
private static Gson gson = new Gson();
private GsonUtil() {
}
/**
* json
* @param obj
* @return String
*/
public static String objectToJsonStr(Object obj){
String jsonStr = null;
jsonStr = gson.toJson(obj);
return jsonStr;
}
/**
* json ( )
*
* @param obj
* @return String
*/
public static String objectToJsonDateSerializer(Object obj,
final String dateformat) {
String jsonStr = null;
gson = new GsonBuilder()
.registerTypeHierarchyAdapter(Date.class,
new JsonSerializer<Date>() {
@Override
public JsonElement serialize(Date src,Type typeOfSrc, JsonSerializationContext context) {
SimpleDateFormat format = new SimpleDateFormat(dateformat);
return new JsonPrimitive(format.format(src));
}}
).setDateFormat(dateformat).create();
if (gson != null) {
jsonStr = gson.toJson(obj);
}
return jsonStr;
}
/**
* json list
* @param jsonStr
* @return
*/
public static List<?> jsonToList(String jsonStr) {
List<?> objList = null;
if (gson != null) {
java.lang.reflect.Type type = new com.google.gson.reflect.TypeToken<List<?>>() {}.getType();
objList = gson.fromJson(jsonStr, type);
}
return objList;
}
/**
* json list ,
* @param jsonStr
* @param type
* @return
*/
public static List<?> jsonToList(String jsonStr, java.lang.reflect.Type type) {
List<?> objList = null;
if (gson != null) {
objList = gson.fromJson(jsonStr, type);
}
return objList;
}
/**
* json map
*
* @param jsonStr
* @return
*/
public static Map<?, ?> jsonToMap(String jsonStr) {
Map<?, ?> objMap = null;
if (gson != null) {
java.lang.reflect.Type type = new com.google.gson.reflect.TypeToken<Map<?, ?>>() {
}.getType();
objMap = gson.fromJson(jsonStr, type);
}
return objMap;
}
/**
* json bean
*
* @param jsonStr
* @return
*/
public static Object jsonToBean(String jsonStr, Class<?> cl) {
Object obj = null;
if (gson != null) {
obj = gson.fromJson(jsonStr, cl);
}
return obj;
}
/**
* json bean
*
* @param jsonStr
* @param cl
* @return
*/
@SuppressWarnings("unchecked")
public static <T> T jsonToBeanDateSerializer(String jsonStr, Class<T> cl,
final String pattern) {
Object obj = null;
gson = new GsonBuilder()
.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
@Override
public Date deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context)
throws JsonParseException {
SimpleDateFormat format = new SimpleDateFormat(pattern);
String dateStr = json.getAsString();
try {
return format.parse(dateStr);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
}).setDateFormat(pattern).create();
if (gson != null) {
obj = gson.fromJson(jsonStr, cl);
}
return (T) obj;
}
/**
* json key
* @param jsonStr
* @param key
* @return
*/
public static Object getJsonValue(String jsonStr, String key) {
Object rulsObj = null;
Map<?, ?> rulsMap = jsonToMap(jsonStr);
if (rulsMap != null && rulsMap.size() > 0) {
rulsObj = rulsMap.get(key);
}
return rulsObj;
}
public static void main(String[] args) {
UserInfo userInfo = new UserInfo();
userInfo.setId("10001");
userInfo.setUsername(" ");
userInfo.setFace("common");
userInfo.setBirthday(new Date());
String json = GsonUtil.objectToJsonDateSerializer(userInfo, "yyyy-MM-dd");
System.out.println(json);
//String jsonStr = "[{\"id\":\"10001\",\"username\":\" \",\"face\":\"common\",\"birthday\":\"2016-04-25\"},{\"id\":\"10002\",\"username\":\"lisi\",\"face\":\"common\",\"birthday\":\"2016-04-25\"}]";
String jsonStr = "[{id:'10001',username:' ',face:'common',birthday:'2016-04-25'},{id:\"10002\",username:\"lisi\",face:\"common\",birthday:\"2016-04-25\"}]";
List<UserInfo> ll = GsonUtil.jsonToBeanDateSerializer(jsonStr, List.class, "yyyy-MM-dd");
System.out.println(ll);
}
}
출력:
{"id":"10001","username":" ","face":"common","birthday":"2016-04-25"}
[{id=10001, username= , face=common, birthday=2016-04-25}, {id=10002, username=lisi, face=common, birthday=2016-04-25}]
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
콘텐츠 SaaS | JSON 스키마 양식 빌더Bloomreach Content를 위한 JSON Form Builder 맞춤형 통합을 개발합니다. 최근 Bloomreach Content SaaS는 내장 앱 프레임워크를 사용하여 혁신적인 콘텐츠 유형 필드를 구축할...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.