本任务为:从数据库表tb_titles_en中取出字段subject(此字段保存的是json数据),要求取得此json其中之一个属性值,并去除重复数据、去小数。
一、建立实体类LseTitlesEn,创建查询Dao,直至可以查询出数据来(此步骤在此省略)。
二、根据json属性创建javabean如下:
public class Subj { private String coden; private String dewey; private String lc; private String subject; public String getCoden() { return coden; } public void setCoden(String coden) { this.coden = coden; } public String getDewey() { return dewey; } public void setDewey(String dewey) { this.dewey = dewey; } public String getLc() { return lc; } public void setLc(String lc) { this.lc = lc; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } }
三、创建json处理类,如下:
/** * 将对象转json,json转对象 * */ public class JsonUtil { /** * 将对象转json * * @param obj * @return * @throws IOException */ public static String obj2Json(Object obj) throws IOException { StringWriter stringWriter = new StringWriter(); JsonGenerator jsonGenerator = null; try { jsonGenerator = new JsonFactory().createJsonGenerator(stringWriter); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.writeValue(jsonGenerator, obj); } catch (IOException e) { throw e; } finally { if (null != jsonGenerator) { try { jsonGenerator.close(); } catch (IOException e) { throw e; } } } return stringWriter.getBuffer().toString(); } /** * son转对象 * * @param json * @param cls * @return * @throws Exception */ public static Object json2Obj(String json, Class cls) throws Exception { ObjectMapper mapper = new ObjectMapper(); Object o = null; try { o = mapper.readValue(json, cls); return o; } catch (Exception e) { throw e; } } }
四、创建输入类Writer:
public class Writer { public static void writer(List<String> str) throws IOException { FileWriter fileWriter = new FileWriter("E:\\dewey.xls"); List<String> subject = str; for (String string : subject) { fileWriter.write(string + "\r\n"); } fileWriter.flush(); fileWriter.close(); } /** * 去重、去小数 * * @param str * @throws IOException */ public static void setWriter(Set<Integer> str) throws IOException { FileWriter fileWriter = new FileWriter("E:\\dewey.xls"); Set<Integer> set = str; for (Integer integer : set) { fileWriter.write(integer + "\r\n"); } fileWriter.flush(); fileWriter.close(); } }
public class DefaultInitServiceTest { @Resource private IDefaultInitService defaultInitService; @Test public void testFindTitleEn() throws Exception { List<String> subject = defaultInitService.searchTitleEn(); // 去重、去小数 Set<Integer> set = new HashSet<Integer>(); for (String string : subject) { Subj su = (Subj) JsonUtil.json2Obj(string, Subj.class); String str = su.getDewey(); // System.out.println(str); if (str != "") { if (str.contains(",")) { String[] s = str.split(","); for (String str2 : s) { double d1 = Double.valueOf(str2); int i = (int) d1; set.add(i); } } else { double d2 = Double.valueOf(str); int j = (int) d2; set.add(j); } } } System.out.println(set); Writer.setWriter(set); } }