Java 类javax.json.JsonWriter 实例源码

项目:incubator-tamaya-sandbox    文件:ConfigurationServices.java   
@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();
}
项目:aws-iot-mqtt-load-generator    文件:ConfigsResource.java   
/**
 * 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();
}
项目:aws-iot-mqtt-load-generator    文件:MetricsSeriesCollectionResource.java   
/**
 * 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();        
}
项目:Java-EE-7-Development-with-NetBeans-8    文件:JsonPModelApiBean.java   
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";
}
项目:LevelEditor    文件:EditorWindow.java   
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);
  }
}
项目:path-optimizer    文件:JsonUtils.java   
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;
    }
项目:cookjson    文件:CookJsonProviderTest.java   
@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 ());
}
项目:cookjson    文件:BuilderTest.java   
@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 ());
}
项目:cookjson    文件:BuilderTest.java   
@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 ());
}
项目:editor-backend    文件:AsciidocMessageEncoder.java   
@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();
}
项目:editor-backend    文件:NotificationMessageEncoder.java   
@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();
}
项目:TundraJSON.java    文件:IDataJSONParser.java   
/**
 * 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();
}
项目:takes    文件:RsPrettyJson.java   
/**
 * 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();
}
项目:tool.lars    文件:DataModelSerializer.java   
/**
 * 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);
    }
}
项目:porcupine    文件:HttpHeaderStatisticInjector.java   
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();
}
项目:openid-connect    文件:JsonWebKeySetProvider.java   
@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();
}
项目:openid-connect    文件:JsonWebKeyProvider.java   
@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();
}
项目:reminders    文件:UserWriter.java   
@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());
    }
}
项目:reminders    文件:ReminderListWriter.java   
@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());
    }
}
项目:reminders    文件:UserListWriter.java   
@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());
    }
}
项目:reminders    文件:ReminderWriter.java   
@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());
    }
}
项目:reminders    文件:ListListWriter.java   
@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());
    }
}
项目:reminders    文件:ListWriter.java   
@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());
    }
}
项目:pp-db-collector-template    文件:StageResultToJsonConverterTest.java   
@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);
}
项目:RaspberryPiBeaconParser    文件:GimbalManagerProxy.java   
@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;
}
项目:johnzon    文件:JsrMessageBodyWriter.java   
@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();
        }
    }
}
项目:johnzon    文件:JsonGeneratorImplTest.java   
@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());
}
项目:johnzon    文件:JsonGeneratorImplTest.java   
@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());
}
项目:johnzon    文件:ServerReport.java   
@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();
}
项目:JavaIncrementalParser    文件:DOMGeneratorTest.java   
@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);
}
项目:jsonix-schema-compiler    文件:TargetDirectoryJsonStructureWriter.java   
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;
}
项目:crest    文件:JSonP.java   
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);
    }
}
项目:poi-visualizer    文件:POIMainFrame.java   
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);
        }
    }
}
项目:launcher-backend    文件:JsonOperations.java   
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;
}
项目:AccessConverter    文件:AccessConverter.java   
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());
}
项目:JSON-Processing-with-Java-EE    文件:ObjectExample6.java   
public String writeJsonStructure() {

        StringWriter stringWriter = new StringWriter();
        JsonWriter jsonWriter = Json.createWriter(stringWriter);
        jsonWriter.writeObject(new ObjectExample3().buildJsonDocument());
        jsonWriter.close();

        return stringWriter.toString();
    }
项目:hibernate-json-type    文件:JsonJavaTypeDescriptor.java   
@Override
public String toString(JsonStructure value) {
    StringWriter w = new StringWriter();
    JsonWriter jw = wf.createWriter(w);
    jw.write(value);
    return w.toString();
}
项目:bluemix-liberty-microprofile-demo    文件:ReservationJsonAdapter.java   
@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();
}
项目:bluemix-liberty-microprofile-demo    文件:ReservationSetProvider.java   
@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();
}
项目:flowing-retail-old    文件:EventProducer.java   
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();
}