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(); } }
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; }
/** * 普通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(); } }
@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); }
/** * 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(); } }
@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 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; }
@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; }
/** * 对象转换成json字符串 * * @author zhaolei * @created 2011-5-9 * @param o 对象 * @return */ public static String toJsonString(Object o) { try { return objectMapper.writeValueAsString(o); } catch (JsonGenerationException e) { log.error(e.getMessage(), e); } catch (JsonMappingException e) { log.error(e.getMessage(), e); } catch (IOException e) { log.error(e.getMessage(), e); } return null; }
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 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 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 <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; }
@Override protected void writeInternal(Object o, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { JsonEncoding encoding = getEncoding(outputMessage.getHeaders().getContentType()); JsonGenerator jsonGenerator = this.objectMapper.getJsonFactory().createJsonGenerator(outputMessage.getBody(), encoding); try { if (this.prefixJson) { jsonGenerator.writeRaw("{} && "); } this.objectMapper.writeValue(jsonGenerator, o); } catch (JsonGenerationException ex) { throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex); } }
@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(); } }
public static User parseUser(String jsonString) { User user = null; ObjectMapper mapper = new ObjectMapper(); mapper.setDateFormat(new SimpleDateFormat("dd-MM-yyyy", new Locale("nl", "NL"))); mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); try { user = mapper.readValue(jsonString, User.class); } catch (JsonGenerationException e) { Log.e("User", e.getMessage()); } catch (JsonMappingException e) { Log.e("User", e.getMessage()); } catch (IOException e) { Log.e("User", e.getMessage()); } return user; }
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); }
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(); } }
@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(); }
@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(); } }
@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(); } } }
/* * (non-Javadoc) * * @see javax.servlet.jsp.tagext.TagSupport#doStartTag() */ @Override public int doStartTag() throws JspException { HttpServletRequest request = (HttpServletRequest) pageContext.getRequest(); try { Map<String, Object> result = null; if ("download".equalsIgnoreCase(mode)) { result = download(); } else { result = new HashMap<String, Object>(); result.put("Error", "Missing or invalid mode parameter"); result.put("Code", -1); } if (logger.isInfoEnabled()) { logger.info(mapper.writeValueAsString(result)); } mapper.writeValue(pageContext.getOut(), result); } catch (JsonMappingException jme) { if (logger.isErrorEnabled()) { logger.error(jme.getMessage()); logger.error(jme.getStackTrace()); } throw new JspException(jme); } catch (JsonGenerationException jge) { if (logger.isErrorEnabled()) { logger.error(jge.getMessage()); logger.error(jge.getStackTrace()); } throw new JspException(jge); } catch (IOException ioe) { if (logger.isErrorEnabled()) { logger.error(ioe.getMessage()); logger.error(ioe.getStackTrace()); } throw new JspException(ioe); } return TagSupport.SKIP_BODY; }
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 void execute() { Connection dbConn = null; CallableStatement proc = null; try { dbConn = PostgresConnection.getDataSource().getConnection(); dbConn.setAutoCommit(true); if (map.containsKey("image_url")) { proc = dbConn.prepareCall("{? = call create_dm(?,?,?,now()::timestamp,?))}"); } else { proc = dbConn.prepareCall("{? = call create_dm(?,?,?,now()::timestamp)}"); } proc.setPoolable(true); proc.registerOutParameter(1, Types.BOOLEAN); proc.setInt(2, Integer.parseInt(map.get("sender_id"))); proc.setInt(3, Integer.parseInt(map.get("reciever_id"))); proc.setString(4, map.get("dm_text")); if (map.containsKey("image_url")) { proc.setString(5, map.get("image_url")); } proc.execute(); boolean sent = proc.getBoolean(1); if (sent) { MyObjectMapper mapper = new MyObjectMapper(); JsonNodeFactory nf = JsonNodeFactory.instance; ObjectNode root = nf.objectNode(); root.put("app", map.get("app")); root.put("method", map.get("method")); root.put("status", "ok"); root.put("code", "200"); try { CommandsHelp.submit( map.get("app"), mapper.writeValueAsString(root), map.get("correlation_id"), LOGGER); } catch (JsonGenerationException e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); } catch (JsonMappingException e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); } catch (IOException e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); } } else { CommandsHelp.handleError( map.get("app"), map.get("method"), "You can not dm a user who is not following you", map.get("correlation_id"), LOGGER); } } catch (PSQLException e) { if (e.getMessage().contains("value too long")) { CommandsHelp.handleError( map.get("app"), map.get("method"), "DM length cannot exceed 140 character", map.get("correlation_id"), LOGGER); } else { CommandsHelp.handleError( map.get("app"), map.get("method"), e.getMessage(), map.get("correlation_id"), LOGGER); } LOGGER.log(Level.SEVERE, e.getMessage(), e); } catch (SQLException e) { CommandsHelp.handleError( map.get("app"), map.get("method"), e.getMessage(), map.get("correlation_id"), LOGGER); LOGGER.log(Level.SEVERE, e.getMessage(), e); } finally { PostgresConnection.disconnect(null, proc, dbConn); } }