當前位置: 首頁>>代碼示例>>Java>>正文


Java JsonWriter類代碼示例

本文整理匯總了Java中javax.json.JsonWriter的典型用法代碼示例。如果您正苦於以下問題:Java JsonWriter類的具體用法?Java JsonWriter怎麽用?Java JsonWriter使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


JsonWriter類屬於javax.json包,在下文中一共展示了JsonWriter類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: writeTo

import javax.json.JsonWriter; //導入依賴的package包/類
@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());
    }
}
 
開發者ID:svanimpe,項目名稱:reminders,代碼行數:20,代碼來源:ListWriter.java

示例2: deleteConfig

import javax.json.JsonWriter; //導入依賴的package包/類
@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();
}
 
開發者ID:apache,項目名稱:incubator-tamaya-sandbox,代碼行數:20,代碼來源:ConfigurationServices.java

示例3: getJson

import javax.json.JsonWriter; //導入依賴的package包/類
/**
 * 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();
}
 
開發者ID:awslabs,項目名稱:aws-iot-mqtt-load-generator,代碼行數:27,代碼來源:ConfigsResource.java

示例4: getJson

import javax.json.JsonWriter; //導入依賴的package包/類
/**
 * 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();        
}
 
開發者ID:awslabs,項目名稱:aws-iot-mqtt-load-generator,代碼行數:23,代碼來源:MetricsSeriesCollectionResource.java

示例5: generateJson

import javax.json.JsonWriter; //導入依賴的package包/類
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";
}
 
開發者ID:PacktPublishing,項目名稱:Java-EE-7-Development-with-NetBeans-8,代碼行數:21,代碼來源:JsonPModelApiBean.java

示例6: doSaveProject

import javax.json.JsonWriter; //導入依賴的package包/類
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);
  }
}
 
開發者ID:alex-ac,項目名稱:LevelEditor,代碼行數:18,代碼來源:EditorWindow.java

示例7: toString

import javax.json.JsonWriter; //導入依賴的package包/類
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;
	}
 
開發者ID:biggis-project,項目名稱:path-optimizer,代碼行數:20,代碼來源:JsonUtils.java

示例8: test2

import javax.json.JsonWriter; //導入依賴的package包/類
@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 ());
}
 
開發者ID:coconut2015,項目名稱:cookjson,代碼行數:18,代碼來源:CookJsonProviderTest.java

示例9: testObject

import javax.json.JsonWriter; //導入依賴的package包/類
@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 ());
}
 
開發者ID:coconut2015,項目名稱:cookjson,代碼行數:22,代碼來源:BuilderTest.java

示例10: testArray

import javax.json.JsonWriter; //導入依賴的package包/類
@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 ());
}
 
開發者ID:coconut2015,項目名稱:cookjson,代碼行數:23,代碼來源:BuilderTest.java

示例11: encode

import javax.json.JsonWriter; //導入依賴的package包/類
@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();
}
 
開發者ID:adoc-editor,項目名稱:editor-backend,代碼行數:18,代碼來源:AsciidocMessageEncoder.java

示例12: encode

import javax.json.JsonWriter; //導入依賴的package包/類
@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();
}
 
開發者ID:adoc-editor,項目名稱:editor-backend,代碼行數:19,代碼來源:NotificationMessageEncoder.java

示例13: transform

import javax.json.JsonWriter; //導入依賴的package包/類
/**
 * 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();
}
 
開發者ID:yegor256,項目名稱:takes,代碼行數:23,代碼來源:RsPrettyJson.java

示例14: serializeAsStream

import javax.json.JsonWriter; //導入依賴的package包/類
/**
 * 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);
    }
}
 
開發者ID:WASdev,項目名稱:tool.lars,代碼行數:23,代碼來源:DataModelSerializer.java

示例15: serializeStatistics

import javax.json.JsonWriter; //導入依賴的package包/類
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();
}
 
開發者ID:AdamBien,項目名稱:porcupine,代碼行數:24,代碼來源:HttpHeaderStatisticInjector.java


注:本文中的javax.json.JsonWriter類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。