// 커뮤니티 상세보기의 정보 수정 @RequestMapping(value = "/insertUserComtBasicInfo") public void setInsertUserComtBasicInfo( @RequestParam Map<String, Object> paramMap, HttpServletResponse response, Authentication authentication) throws IOException { // Spring Security의 Authentication 객를 주입 MemberInfo memberInfo = (MemberInfo) authentication.getPrincipal(); paramMap.put("compId", memberInfo.getCompId()); paramMap.put("userId", memberInfo.getUserId()); String txtMastGubun = (String) paramMap.get("txtMastGubun"); String[] mg_arr = ((String) paramMap.get("txtMastGubun")).split(","); int rows = 0; int cntRw = 0; cntRw = communityService.getInserComtBasicInfoNm(paramMap); if (cntRw > 0) { rows = 99; } else { rows = communityService.setInsertUserComtBasicInfo(paramMap); } try { ObjectMapper mapper = new ObjectMapper(); response.setContentType("application/json"); mapper.writeValue(response.getOutputStream(), rows); } catch (Exception e) { throw e; } }
@Override protected void renderMergedOutputModel( Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception { response.reset(); response.setContentType(getContentType()); response.setCharacterEncoding(characterEncoding); // Object bean = model.get(KEY_BEAN_DATA); if (bean == null) { bean = request.getAttribute(KEY_BEAN_DATA); } if (bean == null) { bean = model; } String type = this.determineReqType(request, model); if (TYPE_REQ_JSON.equalsIgnoreCase(type)) { jsonObj.writeValue(response.getWriter(), fix(bean)); } else if (TYPE_REQ_XML.equalsIgnoreCase(type)) { log.error("The 'xml' type for response has not been implemented!"); throw new RuntimeException("The 'xml' type for response has not been implemented!"); } else { log.error("It is not support type of " + type + " for response !"); throw new RuntimeException("It is not support type of " + type + " for response !"); } }
void setNonexistingParts(Map<String, Set<String>> nonExistingParts) throws LensException { if (!nonExistingParts.isEmpty()) { ByteArrayOutputStream out = null; String partsStr; try { ObjectMapper mapper = new ObjectMapper(); out = new ByteArrayOutputStream(); mapper.writeValue(out, nonExistingParts); partsStr = out.toString("UTF-8"); } catch (Exception e) { throw new LensException("Error writing non existing parts", e); } finally { if (out != null) { try { out.close(); } catch (IOException e) { throw new LensException(e); } } } conf.set(NON_EXISTING_PARTITIONS, partsStr); } else { conf.unset(NON_EXISTING_PARTITIONS); } }
<T> String serializeToString(T trigger) throws JsonGenerationException, JsonMappingException, IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); mapper.writeValue(baos, trigger); baos.flush(); return baos.toString(); }
// 커뮤니티 가입신청 처리 @RequestMapping(value = "/insertComtAllInfoUserAdd") public void setInsertComtAllInfoUserAdd( @RequestParam Map<String, Object> paramMap, HttpServletResponse response, Authentication authentication) throws IOException { // Spring Security의 Authentication 객를 주입 MemberInfo memberInfo = (MemberInfo) authentication.getPrincipal(); paramMap.put("userId", memberInfo.getUserId()); paramMap.put("deptId", memberInfo.getDeptId()); paramMap.put("compId", memberInfo.getCompId()); paramMap.put("typeGubun", "C"); paramMap.put("mastGubun", "U"); paramMap.put("inviteYn", "40"); paramMap.put("joinYn", "N"); int rows = 0; rows = communityService.setInsertComtAllInfoUserAdd(paramMap); try { ObjectMapper mapper = new ObjectMapper(); response.setContentType("application/json"); mapper.writeValue(response.getOutputStream(), rows); } catch (Exception e) { throw e; } }
@RequestMapping(value = "/writeComtMainBasic") public void setWriteComtMainBasic( @ModelAttribute ComtVo comtVo, HttpServletResponse response, Authentication authentication) throws Throwable { // Spring Security의 Authentication 객를 주입 MemberInfo memberInfo = (MemberInfo) authentication.getPrincipal(); Map<String, Object> paramMap = getComtBasic(memberInfo); String admActYn = (String) paramMap.get("CUMT_TYPE"); comtVo.setRegUserId(memberInfo.getUserId()); comtVo.setCompId(memberInfo.getCompId()); comtVo.setDeptId(memberInfo.getDeptId()); comtVo.setAdmActYn(admActYn); comtVo.setTypeGubun("C"); comtVo.setMastGubun("M"); comtVo.setJoinYn("Y"); comtVo.setInviteYn("40"); comtVo.setFcComtId(DateTimeUniqueConverter.UNIQUEKEY15()); int addRow = communityService.insertNewComtInfo(comtVo); try { ObjectMapper mapper = new ObjectMapper(); response.setContentType("application/json"); mapper.writeValue(response.getOutputStream(), addRow); } catch (Exception e) { throw e; } // return "redirect:/cumnity/comtMain"; }
@Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { String thisUsersId = req.getParameter("userId"); if ("true".equals(req.getParameter("pingAlive"))) { updateLastAliveTime(thisUsersId); } else { ObjectMapper mapper = new ObjectMapper(); ArrayNode usersArray = mapper.createArrayNode(); for (Map.Entry<String, User> userEntry : users.entrySet()) { if (!thisUsersId.equals(userEntry.getKey())) { User user = userEntry.getValue(); Date now = new Date(); if ((now.getTime() - user.getLastAliveTime().getTime()) / 1000 <= 10) { ObjectNode userJson = mapper.createObjectNode(); userJson.put("user_id", userEntry.getKey()); userJson.put("user_name", user.getName()); usersArray.add(userJson); } } } ObjectNode usersJson = mapper.createObjectNode(); usersJson.put("opponents", usersArray); resp.setContentType("application/json; charset=UTF-8"); mapper.writeValue(resp.getWriter(), usersJson); } }
/** * Map the given object to a {@link TextMessage}. * * @param object the object to be mapped * @param session current JMS session * @param objectMapper the mapper to use * @return the resulting message * @throws JMSException if thrown by JMS methods * @throws IOException in case of I/O errors * @see Session#createBytesMessage */ protected TextMessage mapToTextMessage(Object object, Session session, ObjectMapper objectMapper) throws JMSException, IOException { StringWriter writer = new StringWriter(); objectMapper.writeValue(writer, object); return session.createTextMessage(writer.toString()); }
public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException { ObjectMapper objMapper = new ObjectMapper(); // JsonToJava User user = objMapper.readValue(new File("D:/sirish/work_files/samplejson.json"), User.class); System.out.println("user name is : " + user.getName()); System.out.println("user city is : " + user.getCity()); System.out.println("user job is : " + user.getJob()); for (String str : user.getHobbies()) { System.out.println("user hobbies are : " + str); } User newUser = new User(); newUser.setName("loknath"); newUser.setCity("Odisha"); newUser.setJob("swe"); newUser.setHobbies(new String[] {"browsing", "travelling"}); // JavaToJson objMapper.writeValue(new File("D:/sirish/work_files/sampleoutputjson.json"), newUser); }
@Override protected ProcessorResult processAttribute( Arguments arguments, Element element, String attributeName) { ProductOptionValue productOptionValue = (ProductOptionValue) StandardExpressionProcessor.processExpression( arguments, element.getAttributeValue(attributeName)); ProductOptionValueDTO dto = new ProductOptionValueDTO(); dto.setOptionId(productOptionValue.getProductOption().getId()); dto.setValueId(productOptionValue.getId()); dto.setValueName(productOptionValue.getAttributeValue()); if (productOptionValue.getPriceAdjustment() != null) { dto.setPriceAdjustment(productOptionValue.getPriceAdjustment().getAmount()); } try { ObjectMapper mapper = new ObjectMapper(); Writer strWriter = new StringWriter(); mapper.writeValue(strWriter, dto); element.setAttribute("data-product-option-value", strWriter.toString()); return ProcessorResult.OK; } catch (Exception ex) { LOG.error("There was a problem writing the product option value to JSON", ex); } return null; }
public static void main(String[] args) throws IOException { ObjectMapper mapper = new ObjectMapper(); BufferedReader bufferedReader = new BufferedReader(new FileReader("D:\\Java SE\\src\\json\\jackson_tree_model\\file.json")); JsonNode jsonRoot = mapper.readTree(bufferedReader); JsonNode jsonNode = jsonRoot.path("name"); System.out.println(jsonNode.getTextValue()); JsonNode jsonNode1 = jsonRoot.path("age"); System.out.println(jsonNode1.getTextValue()); JsonNode jsonNode2 = jsonRoot.path("messages"); Iterator<JsonNode> nodeIterator = jsonNode2.getElements(); while (nodeIterator.hasNext()) { JsonNode jsonNode3 = nodeIterator.next(); System.out.println(jsonNode3.getTextValue()); } ((ObjectNode) jsonRoot).put("nickname", "new nickname"); ((ObjectNode) jsonRoot).put("name", "updated name"); ((ObjectNode) jsonRoot).remove("age"); mapper.writeValue(new File("D:\\Java SE\\src\\json\\jackson_tree_model\\file.json"), jsonRoot); }
@Test public void testSerializeToJson() throws Exception { ObjectMapper objectMapper = new ObjectMapper(); StringWriter stringWriter = new StringWriter(); objectMapper.writeValue(stringWriter, sequence); assertNotNull(stringWriter.toString()); }
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 void toJson(Object pojo, Writer writer, boolean prettyPrint) throws JsonMappingException, JsonGenerationException, IOException { JsonGenerator jg = jf.createJsonGenerator(writer); if (prettyPrint) { jg.useDefaultPrettyPrinter(); } m.writeValue(jg, pojo); }
public static void jsonSerialize(Writer writer, Object serializable) { try { ObjectMapper mapper = new ObjectMapper(); mapper.writeValue(writer, serializable); } catch (Throwable t) { throw new RuntimeException(t); } }
private void printWorkItem(WorkItem item, String directory, int qrCodeHeight, int qrCodeWidth) throws WriterException, IOException { String qrCodeFileName = item.getId() + ".jpg"; String qrCodeFilePath = directory + "/" + qrCodeFileName; QRCodeCreator.createQRCode(item.getId(), qrCodeFilePath, qrCodeHeight, qrCodeWidth); ObjectMapper mapper = new ObjectMapper(); mapper.writeValue(new File(directory + "/" + item.getId() + ".json"), item); }
/** * Marshals an {@link Object} to a pretty-printed JSON file. * * @param o * @throws IOException */ public static void toPrettyJsonFile(final Object o, final File f) throws IOException { try { PRETTY_JSON_OBJECT_MAPPER.writeValue(f, o); } catch (final JsonProcessingException jpe) { final String objectAsString = ToStringBuilder.reflectionToString(o, ToStringStyle.SHORT_PREFIX_STYLE); throw new RuntimeException("Failed to JSON marshall: " + objectAsString, jpe); } }
/** 将对象转换成json */ public static String toJson(Object pojo) { StringWriter sw = new StringWriter(); try { JsonGenerator jg = jf.createJsonGenerator(sw); m.writeValue(jg, pojo); } catch (Exception e) { } return sw.toString(); }
/** * Transforms from Java object notation to JSON. * * @param obj the Java object to transform into JSON. * @return {@code String} the json representation for the object. */ public static String toJson(final Object obj) { final StringWriter stringWriter = new StringWriter(); try { om.writeValue(stringWriter, obj); return stringWriter.toString(); } catch (final Exception e) { throw new RuntimeException("error trying to parse json [" + obj + "]", e); } }
void runWrite(int cycles) throws IOException { writeStopWatch.start(); for (int i = 0; i < cycles; i++) { StringBuilderWriter builderWriter = StringBuilderWriter.Cached.cached(); objectMapper.writeValue(builderWriter, master); builderWriter.toString(); } writeStopWatch.stop(); }
/** * Writes an object as a JSON to a file * * @param file Destination file. * @param o Object to write. * @return Whether successful. */ public static boolean writeJsonFile(File file, Object o) { ObjectMapper mapper = new ObjectMapper(); try { mapper.writeValue(file, o); } catch (Exception e) { log.info(String.format("JsonUtils.writeJsonFile(): Unable to write %s", file.getPath())); return false; } return true; }
protected String makeJson(final Map<String, List<String>> roles) { final ObjectMapper mapper = new ObjectMapper(); final StringWriter sw = new StringWriter(); try { mapper.writeValue(sw, roles); return sw.toString(); } catch (final IOException e) { throw new Error(e); } }
public static String toJson(Object pojo, boolean prettyPrint) throws JsonMappingException, JsonGenerationException, IOException { StringWriter sw = new StringWriter(); JsonGenerator jg = jf.createJsonGenerator(sw); if (prettyPrint) { jg.useDefaultPrettyPrinter(); } m.writeValue(jg, pojo); return sw.toString(); }
public static <T> String toJson(final T object) throws JsonGenerationException, JsonMappingException, IOException { final ObjectMapper mapper = new ObjectMapper(); final ByteArrayOutputStream out = new ByteArrayOutputStream(); mapper.writeValue(out, object); return out.toString(); }
public void toJson(File file, ProjectSignature projectSignature) { try { mapper.writeValue(file, projectSignature); } catch (JsonParseException e) { Log.e(getClass().getName(), "Parsing JSON file failed", e); } catch (JsonMappingException e) { Log.e(getClass().getName(), "Mapping JSON file failed", e); } catch (IOException e) { Log.e(getClass().getName(), "Reading JSON file failed", e); } }
public static String getJSON(Object obj) throws IOException { ObjectMapper mapper = new ObjectMapper(); mapper.getSerializationConfig().disable(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS); mapper.getSerializationConfig().disable(SerializationConfig.Feature.WRITE_NULL_MAP_VALUES); mapper.getSerializationConfig().setSerializationInclusion(Inclusion.NON_NULL); Writer sw = new StringWriter(); mapper.writeValue(sw, obj); sw.flush(); sw.close(); return sw.toString(); }
public static String beanToJson(Object bean) { StringWriter sw = new StringWriter(); try { JsonGenerator jsongenerator = objmapper.getJsonFactory().createJsonGenerator(sw); objmapper.writeValue(jsongenerator, bean); jsongenerator.close(); } catch (IOException e) { LOG.error("", e); return ""; } return sw.toString(); }
@RequestMapping(value = "/getComtInfoCnt") public void getComtInfoCnt( @RequestParam Map<String, Object> paramMap, HttpServletResponse response) throws Throwable { int addRow = communityService.getCommunityCnt(paramMap); try { ObjectMapper mapper = new ObjectMapper(); response.setContentType("application/json"); mapper.writeValue(response.getOutputStream(), addRow); } catch (Exception e) { throw e; } }
/** Converts the object to a JSON string */ public static String toJSON(Object value) { ObjectMapper mapper = new ObjectMapper(); try { StringWriter writer = new StringWriter(); mapper.writeValue(writer, value); return writer.toString(); } catch (RuntimeException ex) { throw ex; } catch (Exception ex) { throw new RuntimeException(ex); } }
@POST @Path("/datatablesquery") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public String queryParameterDatabaseForDataTables(List<Map<String, String>> dataTablesAoData) throws JsonGenerationException, JsonMappingException, IOException { String result = null; final ParameterQuerySender parameterQuerySenderService = (ParameterQuerySender) getServiceTracker().getService(); if (parameterQuerySenderService != null) { Map<String, String> aoData = refineAoDataList(dataTablesAoData); if (aoData != null) { if (LOG.isTraceEnabled()) { LOG.trace("Querying with aoData:" + aoData); } DBObject query = buildMongoQuery(aoData); String skip = aoData.get("iDisplayStart"); String count = aoData.get("iDisplayLength"); String sortCol = calculateSortColumn(aoData); boolean ascending = StringUtils.equals(aoData.get("sSortDir_0"), "asc") ? true : false; Object results = parameterQuerySenderService.query( query, Integer.parseInt(count), Integer.parseInt(skip), sortCol, ascending); // FIXME Put results into aaData and return aoData back to server. if (results instanceof MongoResult) { MongoResult mongoResults = (MongoResult) results; ServerSideProcReturnData aaDataStructure = new ServerSideProcReturnData(); aaDataStructure.sEcho = aoData.get("sEcho"); aaDataStructure.aaData = mongoResults.results; aaDataStructure.iTotalRecords = mongoResults.totalResults; aaDataStructure.iTotalDisplayRecords = aaDataStructure.iTotalRecords; ObjectMapper mapper = new ObjectMapper(); Writer out = new StringWriter(); mapper.writeValue(out, aaDataStructure); result = out.toString(); } else { LOG.error("Object returned from the parameter archiver was not a MongoResult object"); } } else { LOG.error("Invalid aoData received - data was null"); } } else { LOG.warn( "Cannot query parameter archive because there is no " + SERVICE_INTERFACE + " service found."); } return result; }