类com.fasterxml.jackson.core.JsonFactory源码实例Demo

下面列出了怎么用com.fasterxml.jackson.core.JsonFactory的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: data-prep   文件: PreviewConfiguration.java
private List<Long> parseIndexes(final String indexes) {
    if (indexes == null) {
        return null;
    }
    if (indexes.isEmpty()) {
        throw new TDPException(CommonErrorCodes.UNABLE_TO_PARSE_ACTIONS,
                new IllegalArgumentException("Source should not be empty"));
    }
    try {
        final ObjectMapper mapper = new ObjectMapper(new JsonFactory());
        final JsonNode json = mapper.readTree(indexes);

        final List<Long> result = new ArrayList<>(json.size());
        for (JsonNode index : json) {
            result.add(index.longValue());
        }
        return result;
    } catch (IOException e) {
        throw new TDPException(CommonErrorCodes.UNABLE_TO_PARSE_ACTIONS, e);
    }
}
 
源代码2 项目: proctor   文件: JsonParserUtilsTest.java
private static void verifyTestObjectMap(final String testObjectMapAsJsonString) throws IOException {
    final Map<String, TestObject> expected = OBJECT_MAPPER.readValue(
            testObjectMapAsJsonString,
            new TypeReference<Map<String, TestObject>>() {
            }
    );

    final JsonFactory jsonFactory = new JsonFactory();
    final JsonParser jsonParser = jsonFactory.createParser(testObjectMapAsJsonString);

    jsonParser.nextToken();

    final Map<String, TestObject> actual = new HashMap<>();
    JsonParserUtils.consumeJson(
            jsonParser,
            (key, parser) -> {
                final TestObject testObject = OBJECT_MAPPER.readValue(parser, TestObject.class);

                actual.put(key, testObject);
            }
    );

    assertThat(actual).isEqualTo(expected);
}
 
源代码3 项目: pinpoint   文件: ObjectMapperIT.java
@Test
public void testConstructor() throws Exception {
    ObjectMapper mapper1 = new ObjectMapper();
    ObjectMapper mapper2 = new ObjectMapper(new JsonFactory());

    PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
    verifier.printCache();

    Constructor<?> omConstructor = ObjectMapper.class.getConstructor(JsonFactory.class, DefaultSerializerProvider.class, DefaultDeserializationContext.class);
    Constructor<?> omConstructor1 = ObjectMapper.class.getConstructor();
    Constructor<?> omConstructor2 = ObjectMapper.class.getConstructor(JsonFactory.class);
    verifier.verifyTrace(event(SERVICE_TYPE, omConstructor));
    verifier.verifyTrace(event(SERVICE_TYPE, omConstructor1));
    verifier.verifyTrace(event(SERVICE_TYPE, omConstructor));
    verifier.verifyTrace(event(SERVICE_TYPE, omConstructor2));

    verifier.verifyTraceCount(0);
}
 
@Test
public void deserialize_a_serialized_contract_json_document_into_a_contract_object() throws Exception {
    Contract aSimpleContract = aSimpleContract();
    byte[] serializedContract = new ObjectMapper().writeValueAsBytes(aSimpleContract);
    ContractDeserializer contractDeserializer = new ContractDeserializer();

    Contract contract = contractDeserializer.deserialize(new JsonFactory(new ObjectMapper()).createParser(serializedContract), null);

    assertThat(contract.getInput()).extracting("name", "type").containsExactly(
            tuple("name", String.class.getName()),
            tuple("isValid", Boolean.class.getName()),
            tuple("ticket", NodeContractInput.class.getName()));
    assertThat(find(contract.getInput(), instanceOf(NodeContractInput.class)).getInput()).extracting("name", "type").containsExactly(
            tuple("title", String.class.getName()),
            tuple("creationDate", Date.class.getName()),
            tuple("creationLocalDate", LocalDate.class.getName()),
            tuple("creationLocalDateTime", LocalDateTime.class.getName()),
            tuple("creationOffsetDateTime", OffsetDateTime.class.getName()),
            tuple("updateTime", Long.class.getName()));
}
 
源代码5 项目: ipst   文件: HistoDbClientImpl.java
@Override
public List<HistoDbAttributeId> listAttributes() throws IOException {
    List<HistoDbAttributeId> attrs = new ArrayList<>();
    try (InputStream is = httpClient.getHttpRequest(new HistoDbUrl(config, "metadata.json", ImmutableMap.of("colRange", "*")))) {
        JsonFactory jfactory = new JsonFactory();
        try (JsonParser jParser = jfactory.createParser(is)) {
            while (jParser.nextToken() != null) {
                String fieldname = jParser.getCurrentName();
                if ("name".equals(fieldname)) {
                    jParser.nextToken();
                    attrs.add(HistoDbAttributeIdParser.parse(jParser.getText()));
                }
            }
        }
    }
    return attrs;
}
 
源代码6 项目: aws-athena-query-federation   文件: BlockTest.java
/**
 * Temporary 'HACK' - this assertion will fail if the overhead associated with serializing blocks exceeds
 * the hard coded expectation. This is only meaningful for inline blocks which will exceed Lambda's response size.
 * If this assertion fails we need to revisit the default settings in our serialization layer. The serialization
 * layer is currently being refactored and eventually this assertion will not be needed.
 *
 * @param serializedBlock The bytes of the block to serialize.
 * @note https://github.com/awslabs/aws-athena-query-federation/issues/121
 */
private void assertSerializationOverhead(ByteArrayOutputStream serializedBlock)
{
    try {
        ByteArrayOutputStream jout = new ByteArrayOutputStream();
        JsonFactory factory = new JsonFactory();
        JsonGenerator jsonGenerator = factory.createJsonGenerator(jout);
        jsonGenerator.writeBinaryField("field", serializedBlock.toByteArray());
        jsonGenerator.close();
        double overhead = 1 - (((double) serializedBlock.size()) / ((double) jout.size()));
        logger.info("assertSerializationOverhead: {} vs {} = {}", serializedBlock.size(), jout.size(), overhead);
        assertTrue(0.35D > overhead);
    }
    catch (IOException ex) {
        throw new RuntimeException(ex);
    }
}
 
源代码7 项目: openbd-core   文件: CharsToNameCanonicalizer.java
/**
 * Internal constructor used when creating child instances.
 */
private CharsToNameCanonicalizer(CharsToNameCanonicalizer parent, int flags,
        String[] symbols, Bucket[] buckets, int size, int hashSeed, int longestColl) {
    _parent = parent;

    _flags = flags;
    _canonicalize = JsonFactory.Feature.CANONICALIZE_FIELD_NAMES.enabledIn(flags);

    _symbols = symbols;
    _buckets = buckets;
    _size = size;
    _hashSeed = hashSeed;
    // Hard-coded fill factor, 75%
    int arrayLen = (symbols.length);
    _sizeThreshold = _thresholdSize(arrayLen);
    _indexMask =  (arrayLen - 1);
    _longestCollisionList = longestColl;

    // Need to make copies of arrays, if/when adding new entries
    _dirty = false;
}
 
源代码8 项目: ig-json-parser   文件: DeserializeTest.java
@Test
public void fieldAssignmentTest() throws IOException, JSONException {
  final int encodedValue = 25;
  final int deserializedValue = -encodedValue;

  StringWriter stringWriter = new StringWriter();
  JSONWriter writer = new JSONWriter(stringWriter);

  writer.object().key(FormatterUUT.FIELD_ASSIGNMENT_FIELD_NAME).value(encodedValue).endObject();

  String inputString = stringWriter.toString();
  JsonParser jp = new JsonFactory().createParser(inputString);
  jp.nextToken();
  FormatterUUT uut = FormatterUUT__JsonHelper.parseFromJson(jp);

  assertSame(deserializedValue, uut.getFieldAssignmentFormatter());
}
 
源代码9 项目: seldon-server   文件: ClientRPCStoreTest.java
@Test 
public void testDefaultRequestToJSON() throws JsonParseException, IOException, NoSuchMethodException, SecurityException
{
	mockClientConfigHandler.addListener((ClientConfigUpdateListener) EasyMock.anyObject());
	EasyMock.expectLastCall().once();
	replay(mockClientConfigHandler);
	final String client = "test";
	ClientRpcStore store = new ClientRpcStore(mockClientConfigHandler);
	DefaultCustomPredictRequest customRequest =  DefaultCustomPredictRequest.newBuilder().addValues(1.0f).build();

	Any anyMsg = Any.pack(customRequest);
	ClassificationRequestMeta meta = ClassificationRequestMeta.newBuilder().setPuid("1234").build();
	ClassificationRequest request = ClassificationRequest.newBuilder().setMeta(meta).setData(anyMsg).build();
	System.out.println(request);
	JsonNode json = store.getJSONForRequest(client, request);
	Assert.assertNotNull(json);
	System.out.println(json);
	ObjectMapper mapper = new ObjectMapper();
    JsonFactory factory = mapper.getFactory();
    JsonParser parser = factory.createParser(json.toString());
    JsonNode actualObj = mapper.readTree(parser);
    ClassificationRequest req = store.getPredictRequestFromJson(client, actualObj);
    Assert.assertNotNull(req);
    System.out.println(req);
}
 
源代码10 项目: extract   文件: DumpReportTask.java
/**
 * Dump the report as JSON to the given output stream.
 *
 * @param reportMap the report to dump
 * @param output the stream to dump to
 * @param match only dump matching results
 */
private void dump(final ReportMap reportMap, final OutputStream output, final ExtractionStatus match) throws
		IOException {
	final ObjectMapper mapper = new ObjectMapper();
	final SimpleModule module = new SimpleModule();

	module.addSerializer(ReportMap.class, new ReportSerializer(monitor, match));
	mapper.registerModule(module);

	try (final JsonGenerator jsonGenerator = new JsonFactory().setCodec(mapper).createGenerator(output,
			JsonEncoding.UTF8)) {
		jsonGenerator.useDefaultPrettyPrinter();
		jsonGenerator.writeObject(reportMap);
		jsonGenerator.writeRaw('\n');
	}
}
 
源代码11 项目: logging-log4j-audit   文件: CatalogManagerImpl.java
private Map<String, Map<String, CatalogInfo>> initializeData(CatalogReader catalogReader) throws Exception {
    JsonFactory factory = new JsonFactory();
    factory.enable(JsonParser.Feature.ALLOW_COMMENTS);
    ObjectMapper mapper = new ObjectMapper(factory);

    String catalog = catalogReader.readCatalog();
    catalogData = mapper.readValue(catalog, CatalogData.class);

    if (catalogData.getAttributes() != null) {
        for (Attribute attr : catalogData.getAttributes()) {
            if (attr.isRequestContext()) {
                requestContextAttributes.put(attr.getName(), attr);
            }
            Map<String, Attribute> attrMap = attributeMap.computeIfAbsent(attr.getCatalogId(), k -> new HashMap<>());
            attrMap.put(attr.getName(), attr);
        }
    }

    Map<String, Map<String, CatalogInfo>> map = new HashMap<>();
    map.put(DEFAULT_CATALOG, new HashMap<>());
    for (Event event : catalogData.getEvents()) {
        addEntry(map, event);
    }
    return map;
}
 
源代码12 项目: biweekly   文件: JCalRawWriter.java
private void init() throws IOException {
	JsonFactory factory = new JsonFactory();
	factory.configure(Feature.AUTO_CLOSE_TARGET, false);
	generator = factory.createGenerator(writer);

	if (prettyPrint) {
		if (prettyPrinter == null) {
			prettyPrinter = new JCalPrettyPrinter();
		}
		generator.setPrettyPrinter(prettyPrinter);
	}

	if (wrapInArray) {
		generator.writeStartArray();
	}
}
 
源代码13 项目: BIMserver   文件: StreamingModel.java
private void processDownload(Long topicId) throws UserException, ServerException, PublicInterfaceNotFoundException, IfcModelInterfaceException, IOException {
	InputStream inputStream = bimServerClient.getDownloadData(topicId);
	if (inputStream == null) {
		throw new IfcModelInterfaceException("No InputStream to read from for topicId " + topicId);
	}
	InputStream downloadData = new org.bimserver.utils.CountingInputStream(inputStream) {
	};
	try {
		JsonFactory jsonFactory = new JsonFactory();
		JsonParser jp = jsonFactory.createParser(downloadData);
		// TODO implement
	} catch (Exception e) {
		throw new IfcModelInterfaceException(e);
	} finally {
		if (downloadData != null) {
			downloadData.close();
		}
	}
}
 
源代码14 项目: geometry-api-java   文件: TestJsonParser.java
@Test
public void testGeometryToJSONOldID() throws Exception {// CR
	Polygon geom = new Polygon();
	geom.startPath(new Point(-113, 34));
	geom.lineTo(new Point(-105, 34));
	geom.lineTo(new Point(-108, 40));
	String outputPolygon = GeometryEngine.geometryToJson(SpatialReference.create(3857), geom);// Test
																								// WKID
																								// ==
																								// -1
	String correctPolygon = "{\"rings\":[[[-113,34],[-105,34],[-108,40],[-113,34]]],\"spatialReference\":{\"wkid\":102100,\"latestWkid\":3857}}";
	assertTrue(outputPolygon.equals(correctPolygon));
	JsonFactory jf = new JsonFactory();
	JsonParser jp = jf.createJsonParser(outputPolygon);
	jp.nextToken();
	MapGeometry mg = GeometryEngine.jsonToGeometry(jp);
	@SuppressWarnings("unused")
	int srId = mg.getSpatialReference().getID();
	@SuppressWarnings("unused")
	int srOldId = mg.getSpatialReference().getOldID();
	Assert.assertTrue(mg.getSpatialReference().getID() == 3857);
	Assert.assertTrue(mg.getSpatialReference().getLatestID() == 3857);
	Assert.assertTrue(mg.getSpatialReference().getOldID() == 102100);
}
 
源代码15 项目: Canova   文件: Configuration.java
/**
 *  Writes out all the parameters and their properties (final and resource) to
 *  the given {@link Writer}
 *  The format of the output would be
 *  { "properties" : [ {key1,value1,key1.isFinal,key1.resource}, {key2,value2,
 *  key2.isFinal,key2.resource}... ] }
 *  It does not output the parameters of the configuration object which is
 *  loaded from an input stream.
 * @param out the Writer to write to
 * @throws IOException
 */
public static void dumpConfiguration(Configuration conf,
                                     Writer out) throws IOException {
    Configuration config = new Configuration(conf,true);
    config.reloadConfiguration();
    JsonFactory dumpFactory = new JsonFactory();
    JsonGenerator dumpGenerator = dumpFactory.createJsonGenerator(out);
    dumpGenerator.writeStartObject();
    dumpGenerator.writeFieldName("properties");
    dumpGenerator.writeStartArray();
    dumpGenerator.flush();
    for (Map.Entry<Object,Object> item: config.getProps().entrySet()) {
        dumpGenerator.writeStartObject();
        dumpGenerator.writeStringField("key", (String) item.getKey());
        dumpGenerator.writeStringField("value",
                config.get((String) item.getKey()));
        dumpGenerator.writeBooleanField("isFinal",
                config.finalParameters.contains(item.getKey()));
        dumpGenerator.writeStringField("resource",
                config.updatingResource.get(item.getKey()));
        dumpGenerator.writeEndObject();
    }
    dumpGenerator.writeEndArray();
    dumpGenerator.writeEndObject();
    dumpGenerator.flush();
}
 
源代码16 项目: dremio-oss   文件: ProfileWrapper.java
@SuppressWarnings("unused")
public String getFragmentsJSON() throws IOException {
  final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
  final JsonGenerator jsonGenerator = new JsonFactory().createGenerator(outputStream);

  jsonGenerator.writeStartObject();

  for (FragmentWrapper fragmentWrapper : getFragmentProfiles()) {
    fragmentWrapper.addFragment(jsonGenerator);
  }

  jsonGenerator.writeEndObject();

  jsonGenerator.flush();
  return outputStream.toString();
}
 
源代码17 项目: incubator-nemo   文件: MetricStore.java
/**
 * Dumps JSON-serialized string of all stored metric.
 *
 * @return dumped JSON string of all metric.
 * @throws IOException when failed to write file.
 */
public synchronized String dumpAllMetricToJson() throws IOException {
  final ObjectMapper objectMapper = new ObjectMapper();
  final JsonFactory jsonFactory = new JsonFactory();
  final ByteArrayOutputStream stream = new ByteArrayOutputStream();

  try (JsonGenerator jsonGenerator = jsonFactory.createGenerator(stream, JsonEncoding.UTF8)) {
    jsonGenerator.setCodec(objectMapper);

    jsonGenerator.writeStartObject();
    for (final Map.Entry<Class<? extends Metric>, Map<String, Object>> metricMapEntry : metricMap.entrySet()) {
      jsonGenerator.writeFieldName(metricMapEntry.getKey().getSimpleName());
      jsonGenerator.writeStartObject();
      for (final Map.Entry<String, Object> idToMetricEntry : metricMapEntry.getValue().entrySet()) {
        generatePreprocessedJsonFromMetricEntry(idToMetricEntry, jsonGenerator, objectMapper);
      }
      jsonGenerator.writeEndObject();
    }
    jsonGenerator.writeEndObject();
  }

  return stream.toString();
}
 
源代码18 项目: event-streams-samples   文件: MessageList.java
/**
 * Build message list dependent on the format Event Streams requires. The
 * message list is in the form: [{ "value": base_64_string }, ...]
 *
 * @return {String} String representation of a JSON object.
 * @throws IOException
 */
public String build() throws IOException {
    final JsonFactory jsonFactory = new JsonFactory();
    final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    final JsonGenerator jsonGenerator = jsonFactory.createGenerator(outputStream);

    jsonGenerator.writeStartArray();
    for (int i = 0; i < this.messages.size(); i++) {
        jsonGenerator.writeStartObject();
        jsonGenerator.writeFieldName("value");
        jsonGenerator.writeObject(this.messages.get(i));
        jsonGenerator.writeEndObject();
    }
    jsonGenerator.writeEndArray();

    jsonGenerator.close();
    outputStream.close();

    return new String(outputStream.toByteArray());
}
 
源代码19 项目: ure   文件: UVaultSet.java
public void persist(String absoluteFilepath) {
    File file = new File(absoluteFilepath);
    try (
            FileOutputStream stream = new FileOutputStream(file);
            //GZIPOutputStream gzip = new GZIPOutputStream(stream)
    ) {
        JsonFactory jfactory = new JsonFactory();
        JsonGenerator jGenerator = jfactory
                .createGenerator(stream, JsonEncoding.UTF8);
        jGenerator.setCodec(new ObjectMapper());
        jGenerator.writeObject(this);
        jGenerator.close();
    } catch (IOException e) {
        throw new RuntimeException("Couldn't persist object " + toString(), e);
    }
}
 
源代码20 项目: buck   文件: AuditActionGraphCommand.java
/**
 * Dump basic information about the action graph to the given stream in a simple JSON format.
 *
 * <p>The passed in stream is not closed after this operation.
 */
private static void dumpAsJson(
    ActionGraph graph,
    ActionGraphBuilder actionGraphBuilder,
    boolean includeRuntimeDeps,
    NodeView nodeView,
    OutputStream out)
    throws IOException {
  try (JsonGenerator json =
      new JsonFactory()
          .createGenerator(out)
          .configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false)) {
    json.writeStartArray();
    for (BuildRule node : graph.getNodes()) {
      writeJsonObjectForBuildRule(json, node, actionGraphBuilder, includeRuntimeDeps, nodeView);
    }
    json.writeEndArray();
  }
}
 
源代码21 项目: ig-json-parser   文件: DeserializeTest.java
@Test
public void valueExtractTest() throws IOException, JSONException {
  final int encodedValue = 25;
  final int deserializedValue = 40;

  StringWriter stringWriter = new StringWriter();
  JSONWriter writer = new JSONWriter(stringWriter);

  writer.object().key(FormatterUUT.VALUE_FORMATTER_FIELD_NAME).value(encodedValue).endObject();

  String inputString = stringWriter.toString();
  JsonParser jp = new JsonFactory().createParser(inputString);
  jp.nextToken();
  FormatterUUT uut = FormatterUUT__JsonHelper.parseFromJson(jp);

  assertSame(deserializedValue, uut.getValueFormatter());
}
 
源代码22 项目: usergrid   文件: ResultsLog.java
@Override
public void open() throws IOException {
    synchronized ( isOpen ) {
        if ( isOpen.compareAndSet( false, true ) ) {
            resultCount.set( 0 );

            // write the json header for recording the chop results
            JsonFactory factory = new JsonFactory();
            jgen = factory.createGenerator(  new File( resultsFile.get() ), JsonEncoding.UTF8 );

            if ( prettyPrint.get() ) {
                jgen.useDefaultPrettyPrinter();
            }

            jgen.setCodec( new ObjectMapper() );

            setupJsonStream();

            thread = new Thread( this, "ResultLog Writer" );
            thread.start();
        }
    }
}
 
源代码23 项目: apicurio-registry   文件: ConfigJsServlet.java
/**
 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String ct = "application/javascript; charset=" + StandardCharsets.UTF_8;
    response.setContentType(ct);
    JsonFactory f = new JsonFactory();
    try (JsonGenerator g = f.createGenerator(response.getOutputStream(), JsonEncoding.UTF8)) {
        response.getOutputStream().write("var ApicurioRegistryConfig = ".getBytes("UTF-8")); //$NON-NLS-1$ //$NON-NLS-2$
        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(Include.NON_NULL);
        g.setCodec(mapper);
        g.useDefaultPrettyPrinter();

        ConfigJs config = new ConfigJs();
        config.mode = "prod";

        config.artifacts.url = this.generateApiUrl(request);
        
        config.ui.url = this.generateUiUrl(request);
        config.ui.contextPath = "/ui";
        
        config.features.readOnly = this.isFeatureReadOnly();
        
        g.writeObject(config);

        g.flush();
        response.getOutputStream().write(";".getBytes("UTF-8")); //$NON-NLS-1$ //$NON-NLS-2$
    } catch (Exception e) {
        throw new ServletException(e);
    }
}
 
源代码24 项目: constellation   文件: RestClient.java
/**
 * Generate a json string from a flat Map<String, String> of key and values
 *
 * @param params A Map of key/value pairs
 * @return A json representation of a simple map
 *
 * @throws IOException
 */
private String generateJsonFromFlatMap(final Map<String, String> params) throws IOException {
    final ByteArrayOutputStream json = new ByteArrayOutputStream();
    final JsonFactory jsonFactory = new MappingJsonFactory();
    try (JsonGenerator jg = jsonFactory.createGenerator(json)) {
        jg.writeStartObject();
        for (final Map.Entry<String, String> param : params.entrySet()) {
            jg.writeStringField(param.getKey(), param.getValue());
        }
        jg.writeEndObject();
        jg.flush();
    }

    return json.toString(StandardCharsets.UTF_8.name());
}
 
源代码25 项目: aws-sdk-java-v2   文件: SdkJsonGenerator.java
public SdkJsonGenerator(JsonFactory factory, String contentType) {
    try {
        /**
         * A {@link JsonGenerator} created is by default enabled with
         * UTF-8 encoding
         */
        this.generator = factory.createGenerator(baos);
        this.contentType = contentType;
    } catch (IOException e) {
        throw new JsonGenerationException(e);
    }
}
 
源代码26 项目: constellation   文件: RecordStoreUtilities.java
/**
 * Convert a {@link RecordStore} into a JSON document.
 * <p>
 * The JSON document consist of an array of objects, with each object
 * representing a record in the specified {@link RecordStore}. Each field in
 * each object is corresponds to an entry in the corresponding record of the
 * {@link RecordStore}.
 *
 * @param recordStore The {@link RecordStore} you wish to parse into a JSON
 * document.
 * @return A {@link String} representing a JSON document derived from the
 * specified {@link RecordStore}.
 * @throws IOException If something goes wrong while writing to the JSON
 * document.
 */
public static String toJson(final RecordStore recordStore) throws IOException {
    final String json;
    try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
        try (final JsonGenerator jg = new JsonFactory().createGenerator(outputStream)) {
            jg.writeStartArray();

            if (recordStore != null && recordStore.size() > 0) {
                recordStore.reset();
                while (recordStore.next()) {
                    jg.writeStartObject();
                    for (String key : recordStore.keys()) {
                        final String value = recordStore.get(key);
                        if (value == null) {
                            continue;
                        }
                        jg.writeStringField(key, value);
                    }
                    jg.writeEndObject();
                }
            }
            jg.writeEndArray();
        }
        json = outputStream.toString(StandardCharsets.UTF_8.name());
    }
    return json;
}
 
源代码27 项目: java-jwt   文件: HeaderDeserializerTest.java
@Test
public void shouldNotRemoveKnownPublicClaimsFromTree() throws Exception {
    String headerJSON = "{\n" +
            "  \"alg\": \"HS256\",\n" +
            "  \"typ\": \"jws\",\n" +
            "  \"cty\": \"content\",\n" +
            "  \"kid\": \"key\",\n" +
            "  \"roles\": \"admin\"\n" +
            "}";
    StringReader reader = new StringReader(headerJSON);
    JsonParser jsonParser = new JsonFactory().createParser(reader);
    ObjectMapper mapper = new ObjectMapper();
    jsonParser.setCodec(mapper);

    Header header = deserializer.deserialize(jsonParser, mapper.getDeserializationContext());

    assertThat(header, is(notNullValue()));
    assertThat(header.getAlgorithm(), is("HS256"));
    assertThat(header.getType(), is("jws"));
    assertThat(header.getContentType(), is("content"));
    assertThat(header.getKeyId(), is("key"));

    assertThat(header.getHeaderClaim("roles").asString(), is("admin"));
    assertThat(header.getHeaderClaim("alg").asString(), is("HS256"));
    assertThat(header.getHeaderClaim("typ").asString(), is("jws"));
    assertThat(header.getHeaderClaim("cty").asString(), is("content"));
    assertThat(header.getHeaderClaim("kid").asString(), is("key"));
}
 
@Test
public void handle_NoUnmarshallersAdded_ReturnsGenericAmazonServiceException() throws
                                                                               Exception {
    responseHandler = new JsonErrorResponseHandler(new ArrayList<JsonErrorUnmarshaller>(),
                                                   new JsonErrorCodeParser(),
                                                   JsonErrorMessageParser.DEFAULT_ERROR_MESSAGE_PARSER,
                                                   new JsonFactory());

    AmazonServiceException ase = responseHandler.handle(httpResponse);

    assertNotNull(ase);
}
 
源代码29 项目: presto   文件: TestJsonExtract.java
private static String doExtract(JsonExtractor<Slice> jsonExtractor, String json)
        throws IOException
{
    JsonFactory jsonFactory = new JsonFactory();
    JsonParser jsonParser = jsonFactory.createParser(json);
    jsonParser.nextToken(); // Advance to the first token
    Slice extract = jsonExtractor.extract(jsonParser);
    return (extract == null) ? null : extract.toStringUtf8();
}
 
/**
 * @return {@code com.fasterxml.jackson.databind.ObjectWriter} to serialize {@link BufferedIndex} instances
 */
protected ObjectWriter configuredWriter() {

    ObjectMapper objectMapper = new ExtendedObjectMapper(new JsonFactory())
            .setSerializationInclusion(JsonInclude.Include.NON_EMPTY)
            .configure(SerializationFeature.CLOSE_CLOSEABLE, false)
            .addMixIn(BufferedIndex.class, BulkableActionMixIn.class);

    for (JacksonMixIn mixIn: mixIns) {
        objectMapper.addMixIn(mixIn.getTargetClass(), mixIn.getMixInClass());
    }

    return objectMapper.writerFor(BufferedIndex.class);
}
 
 同包方法