public static String makeFinalParamStringWithSign( String apiId, String messageId, String timestamp, Map<String, Object> params, String secret, String contentKey) { String result = null; if (StringUtils.isNotBlank(apiId) && StringUtils.isNotBlank(messageId) && StringUtils.isNotBlank(timestamp) && StringUtils.isNotBlank(secret)) { Map<String, Object> finalMap = new HashMap<String, Object>(); finalMap.put("ApiId", apiId); finalMap.put("MessageID", messageId); finalMap.put("TimeStamp", timestamp); finalMap.put("Validate", DigestUtils.md5Hex(apiId + secret + timestamp).toUpperCase()); finalMap.putAll(params); ObjectMapper mapper = new ObjectMapper(); try { result = "_data=" + YjBase64Util.encode(mapper.writeValueAsString(finalMap), contentKey); } catch (JsonGenerationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JsonMappingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return result; }
public List<Message<?>> createBroadCastMessages(Message<?> message) { final List<Message<?>> messages = new ArrayList<Message<?>>(); List<PlayerAnswer> playerAnswers = (List<PlayerAnswer>) message.getPayload(); for (PlayerAnswer answer : playerAnswers) { logger.info( answer.getQuestionNumber() + ":" + answer.getPlayerId() + ":" + answer.getChoice()); } for (String connectionId : clients.keySet()) { for (PlayerAnswer answer : playerAnswers) { String data = ""; try { data = objectMapper.writeValueAsString(answer); } catch (JsonGenerationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JsonMappingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } messages.add( MessageBuilder.withPayload(data) .setHeader(IpHeaders.CONNECTION_ID, connectionId) .build()); } } return messages; }
@RequestMapping(value = "/app/", method = RequestMethod.POST) public ResponseEntity<App> createApp(@RequestBody App app, UriComponentsBuilder ucBuilder) { System.out.println("Creating App " + app.getTitle()); if (this.api.getAppService().isExist(app)) { System.out.println("A app with name " + app.getTitle() + " already exist"); return new ResponseEntity<App>(HttpStatus.CONFLICT); } app = this.api.getAppService().createApp(app); HttpHeaders headers = new HttpHeaders(); headers.setLocation(ucBuilder.path("/app/{appid}").buildAndExpand(app.getAppid()).toUri()); ObjectMapper mapper = new ObjectMapper(); try { String jsonString = mapper.writeValueAsString(app); System.out.print(jsonString); } catch (JsonGenerationException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return new ResponseEntity<App>(app, headers, HttpStatus.CREATED); }
@Get @Produces("application/json") public String represent() { String userID = (String) getRequestAttributes().get("id"); User u = userService.findByID(Integer.valueOf(userID), User.class); System.out.println(u); ObjectMapper om = new ObjectMapper(); String value = ""; try { // -- ����writeWithDefaultPrettyPrinter()����������Ϊ�˸�ӵĸ�ʽ�� value = om.writerWithDefaultPrettyPrinter().writeValueAsString(u); } catch (JsonGenerationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JsonMappingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return value; }
/** * 普通ajax请求 * @param request * @param response */ public void generalAjax(SimplEntity entity, HttpServletRequest request,HttpServletResponse response){ AjaxResponseBean ajaxResponseBean=new AjaxResponseBean(); ajaxResponseBean.setStatus("success"); ObjectMapper objectMapper = new ObjectMapper(); /*** * 当表单是通过ajax(jquery)提交的 * 提交上来的表单编码是 UTF-8 (默认) * 服务器做出响应时需要将 response的编码设置成通request请求一样 * 普通表单提交的数据 request.getCharacterEncoding() 为NULL * */ response.setCharacterEncoding(request.getCharacterEncoding()); System.out.println(request.getCharacterEncoding()); try { ajaxResponseBean.setData(objectMapper.writeValueAsString(entity)); System.out.println(ajaxResponseBean.getData()); write(response, ajaxResponseBean); } catch (JsonGenerationException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
/** * easyUiForm 表单 * @param request * @param response */ public void easyUiFormGet(SimplEntity entity ,HttpServletRequest request, HttpServletResponse response){ //System.out.println("cerator"); AjaxResponseBean ajaxResponseBean=new AjaxResponseBean(); ajaxResponseBean.setStatus("success"); ObjectMapper objectMapper = new ObjectMapper(); /*** * 当表单是通过ajax(jquery)提交的 * 提交上来的表单编码是 UTF-8 (默认) * 服务器做出响应时需要将 response的编码设置成通request请求一样 * 普通表单提交的数据 request.getCharacterEncoding() 为NULL * 而easyuifrom 是对于jquery的一个封装 所有一样要使用 而它提交的表单 * request.getCharacterEncoding() 是为 :NULL * 所以设置response.setCharacterEncoding("utf-8"); */ response.setCharacterEncoding("gbk"); System.out.println(request.getCharacterEncoding()); try { ajaxResponseBean.setData(objectMapper.writeValueAsString(entity)); System.out.println(ajaxResponseBean.getData()); write(response, ajaxResponseBean); } catch (JsonGenerationException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
public static void transformarJSON(List<Professor> professores) { ObjectMapper mapper = new ObjectMapper(); try { // convert user object to json string, and save to a file mapper.writeValue(new File("professores.json"), professores); // display to console // System.out.println(mapper.writeValueAsString(professor)); } catch (JsonGenerationException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
@RequestMapping("/addUser6") public void addUser6(User user, PrintWriter out) { log.info("userName is:" + user.getUserName()); log.info("password is:" + user.getPassword()); String json = null; /** 使用Jackson */ ObjectMapper map = new ObjectMapper(); try { json = map.writeValueAsString(user); } catch (JsonGenerationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JsonMappingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } log.info("使用Jackson:" + json); /** 使用fastjson */ json = JSON.toJSONString(user); log.info("使用fastjson:" + json); out.write(json); }
public static String toJsonStr(Object bean) { try { String s = jsonObj.writeValueAsString(fix(bean)); return s; } catch (JsonGenerationException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }
public static <T> T getObject(Class<T> clazz, String output) { T rt = null; ObjectMapper mapper = new ObjectMapper(); try { rt = (T) mapper.readValue(output, clazz); } catch (JsonGenerationException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return rt; }
public static <T> String fromObjectListtoJsonArray(List<T> objects) { ObjectMapper mapper = new ObjectMapper(); String jsonArray = null; try { jsonArray = mapper.writeValueAsString(objects); } catch (JsonGenerationException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return jsonArray; }
public static String toJSON(Object obj) { // String json = JSON.encode(obj); ObjectMapper objectMapper = new ObjectMapper(); String json = ""; try { json = objectMapper.writeValueAsString(obj); } catch (JsonGenerationException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return json; }
public static <T> String fromObjectToJson(T object) { ObjectMapper mapper = new ObjectMapper(); String json = null; try { json = mapper.writeValueAsString(object); } catch (JsonGenerationException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return json; }
@SuppressWarnings("unchecked") public void setMessage(List<String> exr) { try { Map map = new HashMap(); map.put("result", "执行结果:(" + exr.size() + ")"); map.put("content", exr); this.message = new ObjectMapper().writeValueAsString(map); } catch (JsonGenerationException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } result.put("message", this.getMessage()); }
/** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream())); String json = ""; if (br != null) { json = br.readLine(); } ObjectMapper mapper = new ObjectMapper(); getAccount account = mapper.readValue(json, getAccount.class); response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); response.setHeader("Access-Control-Max-Age", "3600"); response.setHeader("Access-Control-Allow-Headers", "x-requested-with"); response.setContentType("application/json"); responseData.clear(); if (account.getloadType().equals("removeOrder")) { String[] accountData = new String[8]; accountData[0] = account.getOrderId(); accountData[1] = account.getAccountId(); accountData[2] = account.getUserId(); accountData[3] = account.getPwd(); accountData[4] = account.getUrl(); accountData[5] = account.getCon(); responseData = removeOrder.main(accountData); } try { mapper.writeValue(response.getOutputStream(), responseData); } catch (JsonGenerationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JsonMappingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
private void parseJSON() { ObjectMapper mapper = new ObjectMapper(); try { // read from file, convert it to user class Business user = mapper.readValue(new File("D:\\temp\\file.json"), Business.class); // display to console System.out.println(user); } catch (JsonGenerationException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
private void testJson(Business input) { String str = null; ObjectMapper mapper = new ObjectMapper(); try { str = mapper.writeValueAsString(input); } catch (JsonGenerationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JsonMappingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("JSON is : " + str); }
@Override public void storeStatistics(ResourceStatistics stats, String location, Job job) throws IOException { Configuration conf = job.getConfiguration(); DataStorage storage = new HDataStorage(new Path(location).toUri(), ConfigurationUtil.toProperties(conf)); ElementDescriptor statFilePath = storage.asElement(location, statFileName); if (!statFilePath.exists() && stats != null) { try { new ObjectMapper().writeValue(statFilePath.create(), stats); } catch (JsonGenerationException e) { log.warn("Unable to write Resource Statistics for " + location); e.printStackTrace(); } catch (JsonMappingException e) { log.warn("Unable to write Resource Statistics for " + location); e.printStackTrace(); } } }
@RequestMapping( value = "list", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public @ResponseBody String getSiteDetails(@RequestParam String userId) { try { return JsonUtil.getJSonString(siteService.getUserSiteDetails(userId)); } catch (JsonGenerationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JsonMappingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; }
/** * 普通ajax请求(GET) * @param request * @param response */ public void generalAjaxGet(SimplEntity entity, HttpServletRequest request,HttpServletResponse response){ AjaxResponseBean ajaxResponseBean=new AjaxResponseBean(); ajaxResponseBean.setStatus("success"); ObjectMapper objectMapper = new ObjectMapper(); System.out.println(request.getCharacterEncoding()); try { ajaxResponseBean.setData(objectMapper.writeValueAsString(entity)); System.out.println(ajaxResponseBean.getData()); write(response, ajaxResponseBean); } catch (JsonGenerationException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
@GET @Path("/book") @Produces(MediaType.APPLICATION_JSON) public Response getBookMetadata() { Book book = new Book(); String bookJSON; try { /*returns json object of a book */ bookJSON = mapper.writeValueAsString(book); return Response.status(200).entity(bookJSON).build(); } catch (JsonGenerationException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return Response.status(500).build(); }
private void saveSurvey(String name, Survey survey) { task.setName(name); survey.setTitle(name); survey.setQuestions(dynamicList.getList()); ObjectMapper mapper = new ObjectMapper(); String json = null; try { json = mapper.writeValueAsString(survey); } catch (JsonGenerationException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } task.putExtra("survey", json); // Save new task editor.saveNewTask(task); }
@Override public void storeSchema(ResourceSchema schema, String location, Job job) throws IOException { Configuration conf = job.getConfiguration(); DataStorage storage = new HDataStorage(new Path(location).toUri(), ConfigurationUtil.toProperties(conf)); ElementDescriptor schemaFilePath = storage.asElement(location, schemaFileName); if (!schemaFilePath.exists() && schema != null) { try { new ObjectMapper().writeValue(schemaFilePath.create(), schema); } catch (JsonGenerationException e) { log.warn("Unable to write Resource Statistics for " + location); e.printStackTrace(); } catch (JsonMappingException e) { log.warn("Unable to write Resource Statistics for " + location); e.printStackTrace(); } } if (printHeaders) { ElementDescriptor headerFilePath = storage.asElement(location, headerFileName); if (!headerFilePath.exists()) { OutputStream os = headerFilePath.create(); try { String[] names = schema.fieldNames(); String fn; for (int i = 0; i < names.length; i++) { fn = ((names[i] == null) ? ("$" + i) : names[i]); os.write(fn.getBytes("UTF-8")); if (i < names.length - 1) { os.write(fieldDel); } else { os.write(recordDel); } } } finally { os.close(); } } } }
@Test public void assertProduct() { try { File jsonFile = new File("/Users/darweshyadav/git/BLConnector-Android/src/test/resources/product.json"); BufferedReader reader = new BufferedReader(new FileReader(jsonFile)); String line = null; String text = ""; while ((line = reader.readLine()) != null) { text += line + "\n"; } reader.close(); Product prod = Product.parseProduct(text); assertTrue(prod != null); } catch (JsonGenerationException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
private Pessoa generatePessoaFromJSON() { ObjectMapper mapper = new ObjectMapper(); Pessoa pessoa = new Pessoa(); try { pessoa = mapper.readValue(new File("pessoa.json"), Pessoa.class); System.out.println(pessoa); } catch (JsonGenerationException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return pessoa; }
@Override public long create(Cluster cluster) { if (cluster.getId() != 0) { return cluster.getId(); } long clusterId = 0; try { // stm = conn.prepareStatement("INSERT INTO // fom_cluster(meta,terms_meta,posts_meta,id_query,id_parent,type) VALUES(?,?,?,?,?,?)", // Statement.RETURN_GENERATED_KEYS); StringWriter strWriter = new StringWriter(); objMapper.writeValue(strWriter, cluster.getMeta()); stm.setString(1, strWriter.toString()); String terms_meta = new String(""); for (int i = 0; i < cluster.getTerms().size(); i++) { if (i != cluster.getTerms().size() - 1) { terms_meta = terms_meta.concat(cluster.getTerms().get(i).getNameScore() + ", "); } else { terms_meta = terms_meta.concat(cluster.getTerms().get(i).getNameScore()); } } stm.setString(2, "{" + terms_meta + "}"); String posts_meta = new String(""); for (int i = 0; i < cluster.getPosts().size(); i++) { posts_meta = posts_meta.concat( Long.toString( DAOFactory.getFactory().getPostDAO().create(cluster.getPosts().get(i))) + " "); } stm.setString(3, posts_meta.trim()); stm.setLong(4, cluster.getOriginatingQuery().getId()); if (cluster.getTypeId() != 1) { stm.setLong(5, DAOFactory.getFactory().getClusterDAO().create(cluster.getParentCluster())); } else { stm.setLong(5, 0); } stm.setInt(6, cluster.getTypeId()); if (cluster.getTypeId() == 2) { stm.setDouble(7, cluster.getMeanLat()); stm.setDouble(8, cluster.getMeanLon()); } else { stm.setDouble(7, 0); stm.setDouble(8, 0); } stm.executeUpdate(); ResultSet generatedKeys = stm.getGeneratedKeys(); if (generatedKeys.next()) { clusterId = generatedKeys.getLong(1); cluster.setId(clusterId); // saveTerms(cluster); // savePosts(cluster); } else { System.err.println("Error creating cluster"); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JsonGenerationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JsonMappingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return clusterId; }