List of usage examples for com.fasterxml.jackson.databind ObjectMapper writer
public ObjectWriter writer()
From source file:org.zalando.jackson.datatype.money.MonetaryAmountSerializerTest.java
@Test public void shouldSerializeWithFormattedAmericanValue() throws JsonProcessingException { final ObjectMapper unit = new ObjectMapper() .registerModule(new MoneyModule(new DefaultMonetaryAmountFormatFactory())); final String expected = "{\"amount\":29.95,\"currency\":\"USD\",\"formatted\":\"USD29.95\"}"; final ObjectWriter writer = unit.writer().with(Locale.US); final String actual = writer.writeValueAsString(Money.of(29.95, "USD")); assertThat(actual, is(expected));//from w ww. j a v a 2 s . c om }
From source file:org.zalando.jackson.datatype.money.MonetaryAmountSerializerTest.java
@Test public void shouldSerializeWithFormattedGermanValue() throws JsonProcessingException { final ObjectMapper unit = new ObjectMapper() .registerModule(new MoneyModule(new DefaultMonetaryAmountFormatFactory())); final String expected = "{\"amount\":29.95,\"currency\":\"EUR\",\"formatted\":\"29,95 EUR\"}"; final ObjectWriter writer = unit.writer().with(Locale.GERMANY); final String actual = writer.writeValueAsString(Money.of(29.95, "EUR")); assertThat(actual, is(expected));/*from w w w . j av a 2s .c o m*/ }
From source file:tachyon.master.InodeFileTest.java
@Test public void writeImageTest() throws IOException { // create the InodeFile and the output streams long creationTime = System.currentTimeMillis(); InodeFile inode1 = new InodeFile("test1", 1, 0, 1000, creationTime); ByteArrayOutputStream os = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(os); ObjectMapper mapper = JsonObject.createObjectMapper(); ObjectWriter writer = mapper.writer(); // write the image inode1.writeImage(writer, dos);/*from w w w.jav a2s . com*/ // decode the element ImageElement decoded = null; decoded = mapper.readValue(os.toByteArray(), ImageElement.class); // test the decoded image element Assert.assertEquals(creationTime, decoded.getLong("creationTimeMs").longValue()); Assert.assertEquals(1, decoded.getInt("id").intValue()); Assert.assertEquals(0, decoded.getInt("parentId").intValue()); Assert.assertEquals(1000, decoded.getInt("blockSizeByte").intValue()); Assert.assertEquals(0, decoded.getLong("length").longValue()); Assert.assertEquals(false, decoded.getBoolean("complete")); Assert.assertEquals(false, decoded.getBoolean("pin")); Assert.assertEquals(false, decoded.getBoolean("cache")); Assert.assertEquals("", decoded.getString("ufsPath")); Assert.assertEquals(-1, decoded.getInt("depId").intValue()); Assert.assertEquals(creationTime, decoded.getLong("lastModificationTimeMs").longValue()); }
From source file:org.apereo.openlrs.model.xapi.Statement.java
@JsonIgnore @Override/*from ww w . j a va 2s . co m*/ public String toJSON() { Logger log = Logger.getLogger(Statement.class); ObjectMapper om = new ObjectMapper(); String rawJson = null; try { rawJson = om.writer().writeValueAsString(this); } catch (JsonProcessingException e) { log.error(e.getMessage(), e); } return rawJson; }
From source file:edu.ucsd.crbs.cws.App.java
License:asdf
public static void uploadPreviewWorkflowFile(final String url, Workflow w) throws Exception { ObjectMapper om = new ObjectMapper(); File tmpFile = File.createTempFile("preview", ".json"); try {// w w w .j a v a2 s . c om BufferedWriter bw = new BufferedWriter(new FileWriter(tmpFile)); ObjectWriter ow = om.writer(); bw.write(ow.writeValueAsString(w)); bw.flush(); bw.close(); RunCommandLineProcess procRunner = new RunCommandLineProcessImpl(); System.out.println("TODO SWITCH THIS TO USE JERSEY CLIENT!!!\n" + "Attempting to run this command: curl -i -X POST --form '" + "_formexamplefile=@" + tmpFile.getAbsolutePath() + "' " + url); String res = procRunner.runCommandLineProcess("curl", "-i", "-X", "POST", "--form", "_formexamplefile=@" + tmpFile.getAbsolutePath(), url); System.out.println("\n"); System.out.println("--------------- URL to Preview ----------------"); System.out.println(res); System.out.println("-----------------------------------------------"); } finally { if (tmpFile != null) { tmpFile.delete(); } } }
From source file:ch.webmate.api.doclet.reporter.swagger2.Swagger2Reporter.java
@Override public boolean writeReport(File outputDirectory, Application application) { ObjectMapper objectMapper = createObjectMapper(); // TODO: support reading existing swagger.json by reading it // using jackson and dozer pojo merge Swagger swagger = Swagger2ModelFactory.INSTANCE.createSwaggerTreeFromApplication(application); try {/*from w ww . j ava 2s . c om*/ objectMapper.writer().writeValue(System.out, swagger); objectMapper.writer().writeValue(new File(outputDirectory, "swagger.json"), swagger); System.out.println(""); } catch (IOException e) { e.printStackTrace(); } return true; }
From source file:fr.treeptik.cloudunit.ports.PortsControllerTestIT.java
private String getString(PortResource portResource, ObjectMapper mapper) throws JsonProcessingException { mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false); ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter(); return ow.writeValueAsString(portResource); }
From source file:models.db.acentera.impl.ProjectImpl.java
public static JSONObject getProjectUserDetails(Long projectId, Long userId, User u) throws Exception { Logger.debug("getProjectUserDetails B1 "); Session s = (Session) HibernateSessionFactory.getSession(); Criteria criteria = s.createCriteria(UserProjects.class); JSONArray jsoProjectUserArray = new JSONArray(); JSONArray jsoUserArray = new JSONArray(); JSONArray jsoProjectIdArray = new JSONArray(); jsoProjectIdArray.add(projectId);//from w w w .j a va 2 s. co m Set<User> proessedUsers = new HashSet<User>(); //Get informations about the current User if its in this project... //User theUser = UserImpl.getUserById(userId); //Verry Bad but we couldn't get the user / project mapping to work properly in restrictions... Logger.debug("getProjectUserDetails B2 "); List<UserProjects> lstUp = (List<UserProjects>) criteria .add(Restrictions.and(Restrictions.eq("project.id", projectId))).list(); Logger.debug("getProjectUserDetails B2a " + lstUp); UserProjects up = null; Iterator<UserProjects> itrUp = lstUp.iterator(); while (itrUp.hasNext() && up == null) { UserProjects tmpUp = itrUp.next(); if (tmpUp.getUser().getId().longValue() == userId) { up = tmpUp; } } Logger.debug("getProjectUserDetails Bb " + up); if (up == null) { Logger.debug("Returning null 2..."); return null; } ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false); mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false); ObjectWriter ow = mapper.writer(); User projectUser = up.getUser(); jsoProjectUserArray.add(projectUser.getId()); JSONObject jsoUser = JSONObject.fromObject(mapper.writeValueAsString(projectUser)); jsoUser.put("project", jsoProjectIdArray); jsoUser.put("project_id", projectId); //get current user Tag only.. //Other tags will be gathered if end-user click on them.. List<ProjectUserTags> tags = ProjectImpl.getUserProjectTags(up); JSONArray jsoTagsArr = new JSONArray(); for (int i = 0; i < tags.size(); i++) { jsoTagsArr.add(JSONObject.fromObject(mapper.writeValueAsString(tags.get(i)))); } //jsoUser.put("tags", mapper.writeValueAsString(userProject.getTags())); jsoUser.put("tags", jsoTagsArr); //Get the current user roles for this project... JSONArray jsRolesArray = new JSONArray(); Set<ProjectTags> userRoles = ProjectImpl.getUserProjectRoles(up); Iterator<ProjectTags> itrRoles = userRoles.iterator(); while (itrRoles.hasNext()) { ProjectTags userProjectRole = itrRoles.next(); JSONObject role = JSONObject.fromObject(ow.writeValueAsString(userProjectRole)); jsRolesArray.add(role); } jsoUser.put("roles", jsRolesArray); jsoUserArray.add(jsoUser); proessedUsers.add(projectUser); JSONObject jso = new JSONObject(); jso.put("users", jsoUserArray); //jsoProject.put("users", jsoProjectUserArray); return jso; }
From source file:org.usd.edu.btl.cli.ConvertBets.java
public void toIplant(String inputS, String output) { ObjectMapper betsMapper = new ObjectMapper(); //create new Jackson Mapper File input = new File(inputS); BETSV1 betsTool; //create new seqTool ObjectWriter iplantWriter = betsMapper.writer().withDefaultPrettyPrinter(); //map input json files to iplant class try {/*from ww w. j a v a2 s.co m*/ betsTool = betsMapper.readValue(input, BETSV1.class); IplantV1 iplantOutput = BETSConverter.toIplant(betsTool); String iplantOutputJson = iplantWriter.writeValueAsString(iplantOutput); //write Json as String if (output == null) { /*===============PRINT JSON TO CONSOLE AND FILES =================== */ System.err.println("************************************************\n" + "*********PRINTING OUT CONVERSION************\n" + "--------------BETS --> Iplant--------------\n" + "************************************************\n"); //print objects as Json using jackson System.err.println("=== iPlant TO BETS JSON - OUTPUT === \n" + iplantOutputJson); } else { System.err.println("Writing to file..."); //write to files iplantWriter.writeValue(new File(output), iplantOutput); System.err.println(output + " has been created successfully"); } } catch (IOException e) { System.out.println(e.getMessage()); } }
From source file:org.usd.edu.btl.cli.ConvertBioextract.java
public void toBets(String inputS, String output) { ObjectMapper mapper = new ObjectMapper(); //create new Jackson Mapper File input = new File(inputS); BioExtV1 bioExtTool;/*from w ww. j a v a2 s.c om*/ try { //map input json files to iplant class bioExtTool = mapper.readValue(input, BioExtV1.class); BETSV1 bets = BioExtConverter.toBETS(bioExtTool); //pass the iplant tool spec, convert to bets ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter(); String betsJson = ow.writeValueAsString(bets); //write Json as String if (output == null) { /*===============PRINT JSON TO CONSOLE AND FILES =================== */ System.out.println("************************************************\n" + "*********PRINTING OUT CONVERSION************\n" + "----------BioExtract --> Bets--------------\n" + "************************************************\n"); //print objects as Json using jackson System.out.println("=== BioExt TO BETS JSON === \n" + betsJson); } else { //write to files ow.writeValue(new File(output), betsJson); System.out.println(output + " has been created successfully"); System.exit(1); } } catch (Exception e) { System.out.println(e.getMessage()); } }