@DELETE @Path("/keys/{key}") public String deleteConfig(@PathParam("key") String key) { deleteCounter.incrementAndGet(); final Configuration config = ConfigurationProvider.getConfiguration(); if (key.startsWith("/")) { key = key.substring(1); } final Node prevNode = new Node(config, key, "prevNode"); // TODO implement write! value and ttl as input final Node node = new Node(config, key, "node"); final JsonObjectBuilder root = Json.createObjectBuilder().add("action", "delete") .add("node", node.createJsonObject()) .add("prevNode", prevNode.createJsonObject()); final StringWriter writer = new StringWriter(); final JsonWriter jwriter = Json.createWriter(writer); jwriter.writeObject(root.build()); return writer.toString(); }
/** * Retrieves representation of an instance of * com.amazonaws.soderlun.iot.mqttloadapp.ConfigsResource * * @return an instance of java.lang.String */ @GET @Produces("application/json") public String getJson() { List<LoadConfig> configs = LoadConfigsRegistry.getAllConfigs(); JsonArrayBuilder builder = Json.createArrayBuilder(); for (LoadConfig c : configs) { builder.add(Json.createObjectBuilder() .add("id", c.getId()) .add("running", LoadConfigurationRuntimeRegistry.getInstance().isRunning(c.getId())) ); } StringWriter writer = new StringWriter(); try (JsonWriter jw = Json.createWriter(writer)) { jw.writeArray(builder.build()); } return writer.toString(); }
/** * Retrieves representation of an instance of com.amazonaws.soderlun.iot.mqttloadapp.MetricsSeriesCollectionResource * @return an instance of java.lang.String */ @GET @Produces("application/json") public String getJson() { List<RunningLoadConfiguration> configs = LoadConfigurationRuntimeRegistry.getInstance().getAllRunning(); JsonArrayBuilder builder = Json.createArrayBuilder(); for (RunningLoadConfiguration rms : configs) { builder.add(rms.toJsonObject()); } StringWriter writer = new StringWriter(); try (JsonWriter jw = Json.createWriter(writer)) { jw.writeArray(builder.build()); } return writer.toString(); }
public String generateJson() { JsonObjectBuilder jsonObjectBuilder = Json.createObjectBuilder(); JsonObject jsonObject = jsonObjectBuilder. add("firstName", person.getFirstName()). add("middleName", person.getMiddleName()). add("lastName", person.getLastName()). add("gender", person.getGender()). add("age", person.getAge()). build(); StringWriter stringWriter = new StringWriter(); try (JsonWriter jsonWriter = Json.createWriter(stringWriter)) { jsonWriter.writeObject(jsonObject); } setJsonStr(stringWriter.toString()); return "generated_json"; }
private void doSaveProject() { try { OutputStream fileStream = new FileOutputStream(projectFile); OutputStream bufferedStream = new BufferedOutputStream(fileStream); StringWriter stringWriter = new StringWriter(); Map<String, Boolean> config = new HashMap<>(); config.put(JsonGenerator.PRETTY_PRINTING, true); JsonWriter writer = Json.createWriterFactory(config).createWriter( stringWriter); writer.writeObject(project.toJSON().build()); writer.close(); bufferedStream.write(stringWriter.toString().getBytes()); bufferedStream.close(); } catch (Exception ex) { Logger.getLogger(EditorWindow.class.getName()).log(Level.SEVERE, null, ex); } }
public static String toString(final JsonStructure json) { final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); final JsonWriter jsonWriter = getPrettyJsonWriterFactory() .createWriter(outputStream, Charset.forName("UTF-8")); jsonWriter.write(json); jsonWriter.close(); String jsonString; try { jsonString = new String(outputStream.toByteArray(), "UTF8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } return jsonString; }
@Test public void test2 () throws IOException { CookJsonProvider provider = new CookJsonProvider (); File srcFile = new File ("../tests/data/types.json".replace ('/', File.separatorChar)); JsonReader r = provider.createReader (new InputStreamReader (new FileInputStream (srcFile), BOM.utf8)); ByteArrayOutputStream bos = new ByteArrayOutputStream (); JsonWriter w = provider.createWriter (bos); w.write (r.read ()); r.close (); w.close (); Assert.assertEquals (Utils.getString (srcFile).length (), new String (bos.toByteArray (), BOM.utf8).length ()); }
@Test public void testObject () { HashMap<String, Object> config = new HashMap<String, Object> (); CookJsonProvider provider = new CookJsonProvider (); JsonBuilderFactory f = provider.createBuilderFactory (config); JsonObject model = f.createObjectBuilder () .add ("object", f.createObjectBuilder ()) .add ("array", f.createArrayBuilder ()) .add ("double", 1234.5) .add ("number", new CookJsonInt (1234)) .build (); StringWriter sw = new StringWriter (); JsonWriter writer = provider.createWriter (sw); writer.write (model); writer.close (); Assert.assertEquals ("{\"object\":{},\"array\":[],\"double\":1234.5,\"number\":1234}".length (), sw.toString ().length ()); }
@Test public void testArray () { HashMap<String, Object> config = new HashMap<String, Object> (); CookJsonProvider provider = new CookJsonProvider (); JsonBuilderFactory f = provider.createBuilderFactory (config); JsonArray model = f.createArrayBuilder () .add (12345678901234L) .add (1234.5) .add ("quick brown fox") .add (new BigInteger ("123456789012345678901234567890")) .add (f.createArrayBuilder ()) .build (); StringWriter sw = new StringWriter (); JsonWriter writer = provider.createWriter (sw); writer.write (model); writer.close (); Assert.assertEquals ("[12345678901234,1234.5,\"quick brown fox\",123456789012345678901234567890,[]]", sw.toString ()); }
@Override public String encode(AsciidocMessage m) throws EncodeException { StringWriter swriter = new StringWriter(); try (JsonWriter jsonWrite = Json.createWriter(swriter)) { JsonObjectBuilder builder = Json.createObjectBuilder(); builder.add("type", m.getType().toString()) .add("adocId", m.getAdocId()) .add("data", Json.createObjectBuilder() .add("format", m.getFormat().toString()) .add("source", m.getAdocSource()) .add("sourceToMerge", m.getAdocSourceToMerge()!=null?m.getAdocSourceToMerge():"")); jsonWrite.writeObject(builder.build()); } return swriter.toString(); }
@Override public String encode(NotificationMessage m) throws EncodeException { StringWriter swriter = new StringWriter(); try (JsonWriter jsonWrite = Json.createWriter(swriter)) { JsonObjectBuilder builder = Json.createObjectBuilder(); builder.add("type", m.getType().toString()). add("adocId", m.getAdocId()). add( "data", Json.createObjectBuilder() .add("nbConnected", m.getNbConnected()) .add("nbWriters", m.getWriters().size()) .add("writers", toJSON(m.getWriters()))); jsonWrite.writeObject(builder.build()); } return swriter.toString(); }
/** * Returns a JSON representation of the given IData object. * * @param input The IData to convert to JSON. * @return The JSON representation of the IData. */ @Override public String encodeToString(IData input) throws IOException { StringWriter stringWriter = new StringWriter(); JsonWriter writer = jsonWriterFactory.createWriter(stringWriter); IDataCursor cursor = input.getCursor(); Object[] array = IDataUtil.getObjectArray(cursor, "recordWithNoID"); cursor.destroy(); JsonStructure structure; if (array != null) { structure = toJsonArray(array); } else { structure = toJsonObject(input); } writer.write(structure); writer.close(); return stringWriter.toString().trim(); }
/** * Format body with proper indents. * @param body Response body * @return New properly formatted body * @throws IOException If fails */ private static byte[] transform(final InputStream body) throws IOException { final ByteArrayOutputStream res = new ByteArrayOutputStream(); try (JsonReader rdr = Json.createReader(body)) { final JsonObject obj = rdr.readObject(); try (JsonWriter wrt = Json.createWriterFactory( Collections.singletonMap(JsonGenerator.PRETTY_PRINTING, true) ) .createWriter(res) ) { wrt.writeObject(obj); } } catch (final JsonException ex) { throw new IOException(ex); } return res.toByteArray(); }
/** * Convert a POJO into Serialized JSON form. * * @param o the POJO to serialize * @param s the OutputStream to write to.. * @throws IOException when there are problems creating the JSON. */ public static void serializeAsStream(Object o, OutputStream s) throws IOException { try { JsonStructure builtJsonObject = findFieldsToSerialize(o).mainObject; Map<String, Object> config = new HashMap<String, Object>(); config.put(JsonGenerator.PRETTY_PRINTING, true); JsonWriterFactory writerFactory = Json.createWriterFactory(config); JsonWriter streamWriter = writerFactory.createWriter(s); streamWriter.write(builtJsonObject); } catch (IllegalStateException ise) { // the reflective attempt to build the object failed. throw new IOException("Unable to build JSON for Object", ise); } catch (JsonException e) { throw new IOException("Unable to build JSON for Object", e); } }
public String serializeStatistics(Statistics statistics) { JsonObjectBuilder stats = Json.createObjectBuilder(); stats.add("pipelineName", statistics.getPipelineName()); final String handlerName = statistics.getRejectedExecutionHandlerName(); if (handlerName != null) { stats.add("rejectedExecutionHandlerName", handlerName); } stats.add("activeThreadCount", statistics.getActiveThreadCount()); stats.add("completedTaskCount", statistics.getCompletedTaskCount()); stats.add("corePoolSize", statistics.getCorePoolSize()); stats.add("currentThreadPoolSize", statistics.getCurrentThreadPoolSize()); stats.add("largestThreadPoolSize", statistics.getLargestThreadPoolSize()); stats.add("maximumPoolSize", statistics.getMaximumPoolSize()); stats.add("rejectedTasks", statistics.getRejectedTasks()); stats.add("remainingQueueCapacity", statistics.getRemainingQueueCapacity()); stats.add("minQueueCapacity", statistics.getMinQueueCapacity()); stats.add("totalNumberOfTasks", statistics.getTotalNumberOfTasks()); StringWriter writer = new StringWriter(); try (JsonWriter outputWriter = Json.createWriter(writer)) { outputWriter.writeObject(stats.build()); } return writer.toString(); }
@Override public void writeTo(final JsonWebKeySet jwks, final Class<?> type, final Type genericType, final Annotation[] annotations, final MediaType mediaType, final MultivaluedMap<String, Object> httpHeaders, final OutputStream os) throws IOException, WebApplicationException { final MessageBodyWriter<JsonWebKey> writer = providers.getMessageBodyWriter(JsonWebKey.class, JsonWebKey.class, annotations, mediaType); final JsonArrayBuilder keysArray = Json.createArrayBuilder(); for (final JsonWebKey key : jwks.getKeys()) { final ByteArrayOutputStream keyStream = new ByteArrayOutputStream(); writer.writeTo(key, JsonWebKey.class, null, annotations, mediaType, null, keyStream); keyStream.close(); keysArray.add(Json.createReader(new ByteArrayInputStream(keyStream.toByteArray())) .readObject()); } final JsonObject jwksObject = Json.createObjectBuilder() .add("keys", keysArray) .build(); final JsonWriter w = Json.createWriter(os); w.write(jwksObject); w.close(); }
@Override public void writeTo(final JsonWebKey jwks, final Class<?> type, final Type genericType, final Annotation[] annotations, final MediaType mediaType, final MultivaluedMap<String, Object> httpHeaders, final OutputStream os) throws IOException, WebApplicationException { JsonObjectBuilder keyBuilder = Json.createObjectBuilder(); jwks.buildJsonObject(keyBuilder); JsonWriter w = Json.createWriter(os); w.write(keyBuilder.build()); w.close(); }
@Override public void writeTo(User user, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { JsonObjectBuilder jsonUser = Json.createObjectBuilder(); jsonUser.add("username", user.getUsername()); if (user.getFullName() != null) { jsonUser.add("fullName", user.getFullName()); } JsonArrayBuilder roles = Json.createArrayBuilder(); for (Role role : user.getRoles()) { roles.add(role.name()); } jsonUser.add("roles", roles); try (JsonWriter writer = Json.createWriter(entityStream)) { writer.writeObject(jsonUser.build()); } }
@Override public void writeTo(java.util.List<Reminder> reminders, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { JsonArrayBuilder jsonReminderList = Json.createArrayBuilder(); for (Reminder reminder : reminders) { JsonObjectBuilder jsonReminder = Json.createObjectBuilder(); jsonReminder.add("id", reminder.getId()); jsonReminder.add("title", reminder.getTitle()); if (reminder.getDate() != null) { jsonReminder.add("date", reminder.getDate().getTimeInMillis()); } jsonReminderList.add(jsonReminder); } try (JsonWriter writer = Json.createWriter(entityStream)) { writer.writeArray(jsonReminderList.build()); } }
@Override public void writeTo(List<User> users, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { JsonArrayBuilder jsonList = Json.createArrayBuilder(); for (User user : users) { JsonObjectBuilder jsonUser = Json.createObjectBuilder(); jsonUser.add("username", user.getUsername()); if (user.getFullName() != null) { jsonUser.add("fullName", user.getFullName()); } jsonList.add(jsonUser); } try (JsonWriter writer = Json.createWriter(entityStream)) { writer.writeArray(jsonList.build()); } }
@Override public void writeTo(Reminder reminder, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { JsonObjectBuilder jsonReminder = Json.createObjectBuilder(); jsonReminder.add("id", reminder.getId()); jsonReminder.add("title", reminder.getTitle()); if (reminder.getDate() != null) { jsonReminder.add("date", reminder.getDate().getTimeInMillis()); } if (reminder.getLocation() != null) { JsonObjectBuilder jsonLocation = Json.createObjectBuilder(); jsonLocation.add("latitude", reminder.getLocation().getLatitude()); jsonLocation.add("longitude", reminder.getLocation().getLongitude()); jsonReminder.add("location", jsonLocation); } jsonReminder.add("image", reminder.getImage() != null); try (JsonWriter writer = Json.createWriter(entityStream)) { writer.writeObject(jsonReminder.build()); } }
@Override public void writeTo(java.util.List<List> lists, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { JsonArrayBuilder jsonListList = Json.createArrayBuilder(); for (List list : lists) { JsonObjectBuilder jsonList = Json.createObjectBuilder(); jsonList.add("id", list.getId()); jsonList.add("title", list.getTitle()); EntityManagerFactory emf = Persistence.createEntityManagerFactory("RemindersPU"); EntityManager em = emf.createEntityManager(); Query q = em.createNamedQuery("List.findSize").setParameter("list", list); jsonList.add("size", (Long) q.getSingleResult()); em.close(); emf.close(); jsonListList.add(jsonList); } try (JsonWriter writer = Json.createWriter(entityStream)) { writer.writeArray(jsonListList.build()); } }
@Override public void writeTo(List list, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { JsonObjectBuilder jsonList = Json.createObjectBuilder(); jsonList.add("id", list.getId()); jsonList.add("owner", list.getOwner().getUsername()); jsonList.add("title", list.getTitle()); EntityManagerFactory emf = Persistence.createEntityManagerFactory("RemindersPU"); EntityManager em = emf.createEntityManager(); Query q = em.createNamedQuery("List.findSize").setParameter("list", list); jsonList.add("size", (Long) q.getSingleResult()); em.close(); emf.close(); try (JsonWriter writer = Json.createWriter(entityStream)) { writer.writeObject(jsonList.build()); } }
@Test public void publish_shouldConvertStageResultsIntoSchemaCompliantJson() throws IOException { SchemaLookup schemaLookup = new ClasspathSchemaLookup(); ObjectMapper mapper = new ObjectMapper(); JsonFactory jsonFactory = new JsonFactory(mapper); SchemaPassThroughCache cache = new SchemaPassThroughCache(jsonFactory); JsonSchema schema = cache.getSchema(schemaLookup.getSchemaURL("sample_data_schema.json")); StageResultToJsonConverter convertor = new StageResultToJsonConverter(); StageResult result = new StageResult(new LocalDate(), Period.day, "DIGITAL", 15); JsonObject jsonResult = convertor.convert(result); StringWriter writer = new StringWriter(); JsonWriter jsonWriter = Json.createWriter(writer); jsonWriter.writeObject(jsonResult); jsonWriter.close(); List<ErrorMessage> errorMessages = schema.validate(mapper.readTree(writer.toString())); assertEquals(Collections.<ErrorMessage>emptyList(), errorMessages); }
@POST @Path("/api/beacons/{factory_id}/tags") @Override public String setBeaconTags(@PathParam("factory_id") String factoryID, @FormParam("tags") String[] tags) { Client client = ClientBuilder.newClient(); client.register(TrafficLogger.class); client.register(new AuthHeadersRequestFilter(token)); String url = String.format("https://manager.gimbal.com/api/beacons/%s/tags", factoryID); WebTarget target = client.target(url); ResteasyWebTarget rtarget = (ResteasyWebTarget)target; JsonArrayBuilder tagsBuilder = Json.createArrayBuilder(); for(String tag : tags) tagsBuilder.add(tag); JsonObjectBuilder tagsObj = Json.createObjectBuilder(); tagsObj.add("tags", tagsBuilder.build()); StringWriter sw = new StringWriter(); JsonWriter json = Json.createWriter(sw); json.writeObject(tagsObj.build()); json.close(); Entity<String> jsonEntity = Entity.json(sw.toString()); String response = rtarget.request(MediaType.APPLICATION_JSON_TYPE).post(jsonEntity, String.class); return response; }
@Override public void writeTo(final JsonStructure jsonStructure, final Class<?> aClass, final Type type, final Annotation[] annotations, final MediaType mediaType, final MultivaluedMap<String, Object> stringObjectMultivaluedMap, final OutputStream outputStream) throws IOException, WebApplicationException { JsonWriter writer = null; try { writer = factory.createWriter(close ? outputStream : noClose(outputStream)); writer.write(jsonStructure); } finally { if (writer != null) { writer.close(); } } }
@Test public void prettySimpleStructure() { final JsonWriterFactory writerFactory = Json.createWriterFactory(new HashMap<String, Object>() { { put(JsonGenerator.PRETTY_PRINTING, true); } }); StringWriter buffer = new StringWriter(); final JsonWriter writer = writerFactory.createWriter(buffer); writer.write(Json.createObjectBuilder().add("firstName", "John").build()); writer.close(); assertEquals("{\n" + " \"firstName\":\"John\"\n" + "}", buffer.toString()); }
@Test public void prettySimpleWriter() { final JsonWriterFactory writerFactory = Json.createWriterFactory(new HashMap<String, Object>() { { put(JsonGenerator.PRETTY_PRINTING, true); } }); StringWriter buffer = new StringWriter(); final JsonReader reader = Json.createReader(new ByteArrayInputStream("{\"firstName\":\"John\"}".getBytes())); final JsonWriter writer = writerFactory.createWriter(buffer); writer.write(reader.read()); writer.close(); reader.close(); assertEquals("{\n" + " \"firstName\":\"John\"\n" + "}", buffer.toString()); }
@GET @Path("jsr") @Produces(MediaType.APPLICATION_JSON) public String pmessage() { try { if (!JsrServerEndpointImpl.SEMAPHORE.tryAcquire(1, TimeUnit.MINUTES)) { throw new IllegalStateException("acquire failed"); } } catch (final InterruptedException e) { Thread.interrupted(); return null; } // don't setup (+dependency) for just this method the jsr jaxrs provider final StringWriter output = new StringWriter(); final JsonWriter writer = Json.createWriter(output); writer.write(JsrServerEndpointImpl.MESSAGES.iterator().next()); writer.close(); return output.toString(); }
@Test public void testNestedStructure() throws JSONException { JsonObject jsonObject = Json.createObjectBuilder() .add("title", "The Matrix") .add("year", 1999) .add("cast", Json.createArrayBuilder() .add("Keanu Reaves") .add("Laurence Fishburne") .add("Carrie-Anne Moss")) .build(); StringWriter w = new StringWriter(); try (JsonWriter writer = Json.createWriter(w)) { writer.write(jsonObject); } JSONAssert.assertEquals("{\"title\":\"The Matrix\",\"year\":1999,\"cast\":[\"Keanu Reaves\",\"Laurence Fishburne\",\"Carrie-Anne Moss\"]}", w.toString(), JSONCompareMode.STRICT); }
private File writeStructure(final File targetDir, final String directory, final String fileName, JsonStructure structure) throws IOException { Validate.notNull(fileName); final File dir = new File(targetDir, directory); dir.mkdirs(); final File file = new File(dir, fileName); final FileWriter fileWriter = new FileWriter(file); try { final JsonWriter jsonWriter = provider.createWriterFactory( Collections.singletonMap(JsonGenerator.PRETTY_PRINTING, Boolean.TRUE)).createWriter(fileWriter); jsonWriter.write(structure); } finally { try { fileWriter.close(); } catch (IOException ignored) { } } return file; }
public static void format(final String content, final PrintStream out) { final JsonProvider provider = JsonProvider.provider(); try (JsonReader reader = provider.createReaderFactory(Collections.<String, Object>emptyMap()) .createReader(new ByteArrayInputStream(content.getBytes("UTF-8"))); JsonWriter writer = provider.createWriterFactory(singletonMap(JsonGenerator.PRETTY_PRINTING, "true")) .createWriter(new FilterOutputStream(out) { @Override public void close() throws IOException { super.flush(); // stdout shouldnt get closed } });) { writer.write(reader.read()); } catch (final UnsupportedEncodingException e) { throw new IllegalStateException(e); } }
private void updateProperties(final Observable o, final Object arg) { final String props = treeObservable.getProperties(); if (props == null || "".equals(props)) { propertiesArea.setText(""); } else if (!props.startsWith("{")) { propertiesArea.setText(props); } else { try ( StringWriter writer = new StringWriter(); JsonReader jReader = createJsonReader(new StringReader(props)); JsonWriter jWriter = createJsonWriter(writer) ) { jWriter.write(jReader.readObject()); // add comment for ... // numbers to hexadecimal number // class id to class id name, if possible final Matcher mat = PROPERTY_COMMENT.matcher(writer.getBuffer()); final StringBuffer buf = new StringBuffer(); while (mat.find()) { final String match = mat.group(1); final String comment; if (match.contains("-")) { comment = getNameFromClassID(match); } else { final long l = Long.parseLong(mat.group(1)); comment = "0x"+Long.toHexString(l); } mat.appendReplacement(buf, mat.group()+" /*"+comment+"*/"); } mat.appendTail(buf); propertiesArea.setText(buf.toString()); } catch (IOException ex) { propertiesArea.setText(props); } } }
public static Object unwrapJsonObjects(Object entity) { if (entity instanceof JsonObjectBuilder) { JsonObjectBuilder jsonObjectBuilder = (JsonObjectBuilder) entity; entity = jsonObjectBuilder.build(); } if (entity instanceof JsonStructure) { StringWriter buffer = new StringWriter(); JsonWriter writer = Json.createWriter(buffer); writer.write((JsonStructure) entity); writer.close(); return buffer.toString(); } return entity; }
public static void ExitJson(boolean pretyPrint) { JsonObjectBuilder json = Json.createObjectBuilder(); if(result.length() == 0) result = "fail"; json.add("result", result); if(outputFile != null) json.add("outputFile", outputFile.getAbsolutePath()); if(logFile != null) json.add("logFile", logFile.getAbsolutePath()); if(zipFile != null && zipFile.exists()) json.add("zipFile", zipFile.getAbsolutePath()); if(pretyPrint) { Map<String, Object> properties = new HashMap<>(1); properties.put(JsonGenerator.PRETTY_PRINTING, true); StringWriter stringWriter = new StringWriter(); try (JsonWriter jsonWriter = Json.createWriterFactory(properties).createWriter(stringWriter)) { jsonWriter.write(json.build()); } System.out.println(stringWriter.toString()); } else System.out.print(json.build().toString()); }
public String writeJsonStructure() { StringWriter stringWriter = new StringWriter(); JsonWriter jsonWriter = Json.createWriter(stringWriter); jsonWriter.writeObject(new ObjectExample3().buildJsonDocument()); jsonWriter.close(); return stringWriter.toString(); }
@Override public String toString(JsonStructure value) { StringWriter w = new StringWriter(); JsonWriter jw = wf.createWriter(w); jw.write(value); return w.toString(); }
@Override public void toJson(OutputStream os, Reservation reservation) { Objects.requireNonNull(reservation, RESERVATION_ISNT_ALLOWED_TO_BE_NULL); JsonWriter jsonWriter = Json.createWriter(os); jsonWriter.writeObject(toJson(reservation)); jsonWriter.close(); }
@Override public void writeTo(Set<Reservation> set, Class<?> clazz, Type type, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> headers, OutputStream os) throws IOException, WebApplicationException { JsonArrayBuilder arrayBuilder = Json.createArrayBuilder(); Iterator<Reservation> reservations = set.iterator(); while (reservations.hasNext()) { Reservation reservation = reservations.next(); arrayBuilder.add(reservationJsonAdapter.toJson(reservation)); } JsonWriter jsonWriter = Json.createWriter(os); jsonWriter.writeArray(arrayBuilder.build()); jsonWriter.close(); }
public String asString(JsonObjectBuilder builder) { JsonObject jsonObject = builder.build(); StringWriter eventStringWriter = new StringWriter(); JsonWriter writer = Json.createWriter(eventStringWriter); writer.writeObject(jsonObject); writer.close(); return eventStringWriter.toString(); }