java的json與字串之間的轉換
阿新 • • 發佈:2018-12-13
import java.io.IOException;
import org.springframework.util.StringUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonUtils {
private static ObjectMapper objectMapper = new ObjectMapper(); //物件轉字串 public static <T> String obj2String(T obj){ if (obj == null){ return null; } try { return obj instanceof String ? (String) obj : objectMapper.writeValueAsString(obj); } catch (Exception e) { e.printStackTrace(); return null; } } //字串轉物件 public static <T> T string2Obj(String str,Class<T> clazz){ if (StringUtils.isEmpty(str) || clazz == null){ return null; } try { return clazz.equals(String.class)? (T) str :objectMapper.readValue(str,clazz); } catch (IOException e) { e.printStackTrace(); return null; } }
}
- 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
</div>
<link href="https://csdnimg.cn/release/phoenix/mdeditor/markdown_views-8cccb36679.css" rel="stylesheet">
</div>