很实用的数据类型转换以及读取文件中的数据
/* * 001.json转换成对象 * * @param:传入对象,json字符串 * * @return:Object */ public static Object jsonToObj(Object obj, String jsonStr) throws JsonParseException, JsonMappingException, IOException { // System.out.println(
public class Reader { public static String readToString(String fileName) { String encoding = "UTF-8"; File file = new File(fileName); Long filelength = file.length(); byte[] filecontent = new byte[filelength.intValue()]; try { FileInputStream in = new FileInputStream(file); in.read(filecontent); in.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { return new String(filecontent, encoding); } catch (UnsupportedEncodingException e) { System.err.println("The OS does not support " + encoding); e.printStackTrace(); return null; } } }
obj.toString()); // System.out.println(jsonStr); ObjectMapper mapper = new ObjectMapper(); //mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); return obj = mapper.readValue(jsonStr, obj.getClass()); } /* * 002.对象转换成json * * @param:传入对象 * * @return:json字符串 */ public static String objToJson(Object obj) throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); return mapper.writeValueAsString(obj); } public static Map<String, Object> jsonToMap(String jsonString) throws JsonParseException, JsonMappingException, IOException { ObjectMapper MAPPER = new ObjectMapper(); // JavaType jvt = MAPPER.getTypeFactory().constructParametricType(HashMap.class,String.class,String.class); HashMap<String,Object> mmap = MAPPER.readValue(jsonString, HashMap.class); // Map<String,String> urMap = MAPPER.readValue(jsonString, jvt); return mmap; }