A few code snippets about generics

1. The method parameter is a generic type

private <T> List<T> changeDatas(
			List<DataInfo> dataes,Class<T> a) {
		List<T> ans = new ArrayList<T>();
		try {
			if (!CollectionUtils.isEmpty(dataes)) {
				for (DataInfo _data: dataes) {
					T newD = a.newInstance();
					BeanUtils.copyProperties (newD, _data);
					ans.add(newD);
				}
			}
		} catch (Exception e) {
			e.printStackTrace ();
		}
		return ans;
	}

 

2. A tool class written by myself about serialization, deserialization, and json conversion, using an example of generic types

public class MockUtil {
	 
	public static FitSdpShoppingDto morkShoppingDto(){
		return MockUtil.deserializeObject("d:\\cache\\123123123.txt",FitSdpShoppingDto.class);
	}
	
	public static void morkCacheShoopingDto(FitSdpShoppingDto shoppingDto){
		MockUtil.serializeObject(shoppingDto,"d:\\cache\\123123123.txt");
	}
	
	/**
	 * read file
	 * @param fileName
	 * @return
	 */
	public static String readFile(String fileName) {
		InputStream in;
		try {
			in = new FileInputStream(fileName);
			return IOUtils.toString(in, "GBK");

		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace ();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace ();
		}
		return null;
	}

	/**
	 * write to file
	 *
	 * @param fileName
	 * @param content
	 */
	public static void writeFile(String fileName, String contant) {
		PrintWriter out;
		try {
			out = new PrintWriter(new BufferedWriter(new FileWriter(fileName)));
			out.print(contant);
			out.close();
		} catch (IOException e) {
			System.out.println("An exception occurred when reading and writing files!");
		} catch (Exception e) {
			System.out.println("Exception occurred");
		}
	}

	public static void writeJsonToFile(String fileName, Object contant) {
		PrintWriter out;
		try {
			out = new PrintWriter(new BufferedWriter(new FileWriter(fileName)));
			out.print(toJsonStr(contant));
			out.close();
		} catch (IOException e) {
			System.out.println("An exception occurred when reading and writing files!");
		} catch (Exception e) {
			System.out.println("Exception occurred");
		}
	}
	
	/**
	 * Parse json string from json file and convert to java type
	 *
	 * @param name
	 * @param clazz
	 * @return
	 */
	public static <T> T createFromJsonFile(String name, TypeReference clazz) {
		try {
			String sqlFlie = readFile(name);
			String result = sqlFlie;
			if (StringUtils.isNotBlank(result)) {
				ObjectMapper objectMapper = JSONMapper.getInstance();
				return (T) objectMapper.readValue(result, clazz);
			}
			return null;
		} catch (Exception ew) {
			ew.printStackTrace ();
			return null;
		}
	}

	/**
	 * Parse json string from json file and convert to java type
	 *
	 * @param name
	 * @param clazz
	 * @return
	 */
	public static <T> T createFromJsonFile(String name, Class<T> clazz) {
		try {
			String sqlFlie = readFile(name);
			String result = sqlFlie;
			if (StringUtils.isNotBlank(result)) {
				ObjectMapper objectMapper = JSONMapper.getInstance();
				return (T) objectMapper.readValue(result, clazz);
			}
			return null;
		} catch (Exception ew) {
			ew.printStackTrace ();
			return null;
		}
	}

	/**
	 * Save the serialized object to a file.
	 *
	 * @param shoppingDto
	 * @param name
	 */
	public static void serializeObject(Object shoppingDto, String name) {
		ObjectOutputStream oo;
		try {
			oo = new ObjectOutputStream(new FileOutputStream(new File(name)));
			oo.writeObject(shoppingDto);
			System.out.println("Object serialization succeeded!");
			oo.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace ();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace ();
		}

	}

	/**
	 * Deserialize object from file.
	 *
	 * @param name
	 * @param clazz
	 * @return
	 */
	public static <T> T deserializeObject(String name, Class<T> clazz) {
		ObjectInputStream ois;
		try {
			ois = new ObjectInputStream(new FileInputStream(new File(name)));
			T person = (T) ois.readObject();
			System.out.println("Object deserialization succeeded!");
			return person;
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace ();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace ();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace ();
		}
		return null;
	}

	/**
	 * The parsing object is a json string.
	 *
	 * @param obj
	 * @return
	 */
	public static String toJsonStr(Object obj) {
		try {
			return JSONMapper.getInstance().writeValueAsString(obj);
		} catch (Exception e) {
			e.printStackTrace ();
		}
		return null;
	}

	/**
	 * Parse json string into java object.
	 *
	 * @param obj
	 * @param clazz
	 * @return
	 */
	public static <T> T parseJsonStr(String str, Class<T> clazz) {
		try {
			return (T) JSONMapper.getInstance().readValue(str, clazz);
		} catch (Exception e) {
			e.printStackTrace ();
		}
		return null;
	}

	/**
	 * Parse json string into java object.
	 *
	 * @param str
	 * @param clazz
	 * @return
	 */
	public static <T> T parseJsonStr(String str, TypeReference<T> clazz) {
		try {
			ObjectMapper objectMapper = JSONMapper.getInstance();
			objectMapper.configure(
					JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
			return objectMapper.readValue(str, clazz);
		} catch (Exception e) {
			e.printStackTrace ();
		}
		return null;
	}

	public static void main(String[] aegs) throws Exception {
		Long a = 1481694879609L;
		System.out.println(DateUtils.parseDate(a, "yyyy-MM-dd"));;
//		Date d1 = DateUtils.parseDate("2016-12-11");
//		System.out.println(d1.getTime());
//		
//		Date d2 = DateUtils.parseDate("2016-12-13");
//		System.out.println(d2.getTime());
//		String inputStr = readFile("d:\\zipstr.txt");
//		String callRequestStr = ZipUnZipUtils.getInstance().unzipBase642String(inputStr,"UTF-8");
//		System.out.println(callRequestStr);
		 
//		System.out.println(System.currentTimeMillis());
//		FlightSearchResult<FlightSearchFlightInfoDto> goFlightSearchResult2 = MockUtil
//				.createFromJsonFile(
//						"d:\\new_flight.txt",
//						new TypeReference<FlightSearchResult<FlightSearchFlightInfoDto>>() {
//						});

		// String sqlFlie = readFile("d:\\Old query for round-trip tickets.txt");
		// ObjectMapper objectMapper = JSONMapper.getInstance();
		// FlightSearchResult<FlightSearchFlightInfoDto> flightSearchResult =
		// objectMapper
		// .readValue(
		// sqlFlie,
		// new TypeReference<FlightSearchResult<FlightSearchFlightInfoDto>>() {
		// });
		// List<FlightSearchFlightInfoDto> result =
		// flightSearchResult.getResults();
		// for(FlightSearchFlightInfoDto d:result){
		// writeFile("d:\\"+System.currentTimeMillis()+".txt",
		// getJsonStr(d)+"\n\n\n" );
		// }
	}
}

 

3. When parsing json, it may not be able to parse and report an error, use the following jsonmap configuration:

ObjectMapper objectMapper = JSONMapper.getInstance();
			objectMapper.configure(
					JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
			return objectMapper.readValue(str, clazz);

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327037243&siteId=291194637