/**
   * Creates a JSON string with key as 'message' and value as 'username: message'
   *
   * @param username the user who sent message
   * @param msg the message sent by user
   * @return String JSON representation of a single message
   */
  private String buildJsonData(String username, String msg) {
    JsonObject jsonObject =
        Json.createObjectBuilder().add("message", username + ": " + msg).build();
    StringWriter sw = new StringWriter();
    try (JsonWriter jw = Json.createWriter(sw)) {
      jw.write(jsonObject);
    }

    return sw.toString();
  }
예제 #2
0
파일: RsJSON.java 프로젝트: aoesoft/takes
 /**
  * Print JSON.
  *
  * @param src Source
  * @return JSON
  * @throws IOException If fails
  */
 private static byte[] print(final RsJSON.Source src) throws IOException {
   final ByteArrayOutputStream baos = new ByteArrayOutputStream();
   final JsonWriter writer = Json.createWriter(baos);
   try {
     writer.write(src.toJSON());
   } finally {
     writer.close();
   }
   return baos.toByteArray();
 }
 private static void createJsonFile() {
   JsonObject model =
       Json.createObjectBuilder()
           .add("firstName", "Martin")
           .add(
               "phoneNumbers",
               Json.createArrayBuilder()
                   .add(Json.createObjectBuilder().add("mobile", "1234 56789"))
                   .add(Json.createObjectBuilder().add("home", "2345 67890")))
           .build();
   try (JsonWriter jsonWriter =
       Json.createWriter(
           new FileWriter(
               Paths.get(System.getProperty("user.dir"), "target/myData.json").toString()))) {
     jsonWriter.write(model);
   } catch (IOException e) {
     LOGGER.severe("Failed to create file: " + e.getMessage());
   }
 }
예제 #4
0
 @Override
 public JsonResource setContents(JsonStructure structure) {
   if (structure == null) throw new IllegalArgumentException("JsonStructure must not be null.");
   try {
     if (!exists()) {
       getParent().mkdirs();
       if (!createNewFile()) {
         throw new IOException("Failed to create file: " + getUnderlyingResourceObject());
       }
     }
     JsonWriterFactory writerFactory =
         Json.createWriterFactory(Collections.singletonMap(JsonGenerator.PRETTY_PRINTING, true));
     try (OutputStream out =
             getFileOperations().createOutputStream(getUnderlyingResourceObject());
         JsonWriter writer = writerFactory.createWriter(out)) {
       writer.write(structure);
     }
   } catch (IOException e) {
     throw new ResourceException("Error while setting the Json contents", e);
   }
   return this;
 }