Object json 转换为 string
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;
public class JsonUtil {
public static String createJson(Object obj) throws JsonGenerationException, JsonMappingException, IOException {
ObjectMapper mapper = new ObjectMapper();
SerializationConfig config = mapper.getSerializationConfig();
config.setSerializationInclusion(Inclusion.NON_NULL);
Writer writer = new StringWriter();
mapper.writeValue(writer, obj);
return writer.toString();
}
//测试代码
public static void main(String[] args) throws Throwable {
Map<String, Object> map = new HashMap<String, Object>();
map.put("a", "aaa");
map.put("b", "bbb");
System.out.println(createJson(map));
A a = new A();
a.setI(3);
a.setStr("abc");
System.out.println(createJson(a));
A a1 = new A();
a1.setI(0);
System.out.println(createJson(a1));
}
}
class A {
private int i;
private String str;
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
}