Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package com.ces;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
/***
* 对象与JSON字符串转换工具类
* @author Slet
*
*/
public class ObjectMapperUtils {
private static final ObjectMapper mapper=new ObjectMapper();
/**
* 对象-->JSON
* @param data
* @return
*/
public static String toJSON(Object data) {
String json=null;
try {
json=mapper.writeValueAsString(data);
} catch (JsonProcessingException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
return json;
}
/**
* JSON-->对象
* @param <T>
* @param json
* @param clazz
* @return
*/
public static <T>T toObject(String json,Class<T> clazz) {
T t=null;
try {
t = mapper.readValue(json, clazz);
} catch (JsonParseException e) {
e.printStackTrace();
throw new RuntimeException(e);
} catch (JsonMappingException e) {
e.printStackTrace();
throw new RuntimeException(e);
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
return t;
}
}