java对象转换成json

package com.bjs.acrosstime.utils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.codehaus.jackson.annotate.JsonIgnore;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.type.TypeFactory;

/**
* @author Peter
*/
public class JsonUtils {

private static Logger errLogger = Logger.getLogger("error");
private static Logger apiAccessLogger = Logger.getLogger("access");
private static final String PREFIX = "apiAccessAop";

//each thread has its own ObjectMapper instance
private static ThreadLocal<ObjectMapper> objMapperLocal = new ThreadLocal<ObjectMapper>(){
@Override
public ObjectMapper initialValue(){
return new ObjectMapper();
}
};

public static String toJSON(Object value) {
String result = null;
try {
result = objMapperLocal.get().writeValueAsString(value);
} catch (Exception e) {
e.printStackTrace();
} 
// Fix null string
if ("null".equals(result)) {
result = null;
}
return result;
}

public static <T> T toT(String jsonString, Class<T> clazz) {
try {
return objMapperLocal.get().readValue(jsonString, clazz);
} catch (Exception e) {
errLogger.error("toT error: "+ jsonString,e);
} 
return null;
}

public static <T> List<T> toTList(String jsonString, Class<T> clazz) {
try {
return objMapperLocal.get().readValue(jsonString, TypeFactory.collectionType(List.class, clazz));
} catch (Exception e) {
errLogger.error("toTList error: "+ jsonString,e);
} 
return null;
}

@SuppressWarnings("unchecked")
public static Map<String, Object> toMap(String jsonString) {
return toT(jsonString, Map.class);
}

public static void main(String[] args) {
Message msg1 = new Message();
msg1.uid = "1";
msg1.opr_time = new Date();
msg1.content = "hello world---1";

Message msg2 = new Message();
msg2.uid = "2";
msg2.opr_time = new Date();
msg2.content = "hello world---2";

List<Message> list = new ArrayList<Message>();
list.add(msg1);
list.add(msg2);
final String json = toJSON(list);
System.out.println(json);

//String l = "[{"opr_time":"2012-05-12 12:33:22","uid":"akun","content":"u5927u5730u9707u7684u4ebau4eecu5b89u606fu5427"},{"opr_time":"2012-05-12 12:33:25","uid":"requelqi","content":"u6211u56deu5bb6u4e86"},{"opr_time":"2012-05-12 12:37:25","uid":"stone","content":"u4ecau5929u4e0du65b9u4fbfu6e38u620f"}]";
final List<Message> newMsg = JsonUtils.toTList(json, Message.class);
System.out.println(newMsg);
System.out.println((newMsg.get(0).uid));
}

static class Message {
String uid;
Date opr_time;
@JsonIgnore
String content;
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public Date getOpr_time() {
return opr_time;
}
public void setOpr_time(Date opr_time) {
this.opr_time = opr_time;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}

}
原文地址:https://www.cnblogs.com/daohangtaiqian/p/5392002.html