/** Unit test to check for regression of [JACKSON-18]. */
  public void testSmallNumbers() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    ArrayNode root = mapper.createArrayNode();
    for (int i = -20; i <= 20; ++i) {
      JsonNode n = root.numberNode(i);
      root.add(n);
      // Hmmh. Not sure why toString() won't be triggered otherwise...
      assertEquals(String.valueOf(i), n.toString());
    }

    // Loop over 2 different serialization methods
    for (int type = 0; type < 2; ++type) {
      StringWriter sw = new StringWriter();
      if (type == 0) {
        JsonGenerator gen = new JsonFactory().createGenerator(sw);
        root.serialize(gen, null);
        gen.close();
      } else {
        mapper.writeValue(sw, root);
      }

      String doc = sw.toString();
      JsonParser p = new JsonFactory().createParser(new StringReader(doc));

      assertEquals(JsonToken.START_ARRAY, p.nextToken());
      for (int i = -20; i <= 20; ++i) {
        assertEquals(JsonToken.VALUE_NUMBER_INT, p.nextToken());
        assertEquals(i, p.getIntValue());
        assertEquals("" + i, p.getText());
      }
      assertEquals(JsonToken.END_ARRAY, p.nextToken());
      p.close();
    }
  }
  public static String objectToJson(Object object) {

    JsonGenerator jsonGenerator = null;
    ObjectMapper objectMapper = new ObjectMapper();
    ByteArrayOutputStream out = null;
    String json = null;
    try {
      try {

        String jsonStr = "";
        out = new ByteArrayOutputStream();
        jsonGenerator = objectMapper.getFactory().createGenerator(out, JsonEncoding.UTF8);
        jsonGenerator.writeObject(object);
        json = new String(out.toByteArray(), Charset.forName("UTF-8"));
        out.toString();
        System.out.println(json);
      } finally {
        if (jsonGenerator != null) {
          jsonGenerator.flush();
        }
        if (!jsonGenerator.isClosed()) {
          jsonGenerator.close();
        }
        if (out != null) {
          out.close();
        }
        jsonGenerator = null;
        objectMapper = null;
      }
    } catch (Exception e) {

    }
    return json;
  }
  public void testFromMap() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    ObjectNode root = mapper.createObjectNode();
    root.put(FIELD4, TEXT2);
    root.put(FIELD3, -1);
    root.putArray(FIELD2);
    root.put(FIELD1, DOUBLE_VALUE);

    /* Let's serialize using one of two alternate methods:
     * first preferred (using generator)
     * (there are 2 variants here too)
     */
    for (int i = 0; i < 2; ++i) {
      StringWriter sw = new StringWriter();
      if (i == 0) {
        JsonGenerator gen = new JsonFactory().createGenerator(sw);
        root.serialize(gen, null);
        gen.close();
      } else {
        mapper.writeValue(sw, root);
      }
      verifyFromMap(sw.toString());
    }

    // And then convenient but less efficient alternative:
    verifyFromMap(root.toString());
  }
  public void testFromArray() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    ArrayNode root = mapper.createArrayNode();
    root.add(TEXT1);
    root.add(3);
    ObjectNode obj = root.addObject();
    obj.put(FIELD1, true);
    obj.putArray(FIELD2);
    root.add(false);

    /* Ok, ready... let's serialize using one of two alternate
     * methods: first preferred (using generator)
     * (there are 2 variants here too)
     */
    for (int i = 0; i < 2; ++i) {
      StringWriter sw = new StringWriter();
      if (i == 0) {
        JsonGenerator gen = new JsonFactory().createGenerator(sw);
        root.serialize(gen, null);
        gen.close();
      } else {
        mapper.writeValue(sw, root);
      }
      verifyFromArray(sw.toString());
    }

    // And then convenient but less efficient alternative:
    verifyFromArray(root.toString());
  }
 /**
  * Helper method used when value to serialize is {@link Closeable} and its <code>close()</code>
  * method is to be called right after serialization has been called
  */
 private final void _writeCloseable(JsonGenerator jgen, Object value, SerializationConfig cfg)
     throws IOException, JsonGenerationException, JsonMappingException {
   Closeable toClose = (Closeable) value;
   try {
     if (_rootType == null) {
       _serializerProvider(cfg).serializeValue(jgen, value);
     } else {
       _serializerProvider(cfg).serializeValue(jgen, value, _rootType, _rootSerializer);
     }
     JsonGenerator tmpJgen = jgen;
     jgen = null;
     tmpJgen.close();
     Closeable tmpToClose = toClose;
     toClose = null;
     tmpToClose.close();
   } finally {
     /* Need to close both generator and value, as long as they haven't yet
      * been closed
      */
     if (jgen != null) {
       try {
         jgen.close();
       } catch (IOException ioe) {
       }
     }
     if (toClose != null) {
       try {
         toClose.close();
       } catch (IOException ioe) {
       }
     }
   }
 }
 /** Method called to configure the generator as necessary and then call write functionality */
 protected final void _configAndWriteValue(JsonGenerator jgen, Object value)
     throws IOException, JsonGenerationException, JsonMappingException {
   _configureJsonGenerator(jgen);
   // [JACKSON-282]: consider Closeable
   if (_config.isEnabled(SerializationFeature.CLOSE_CLOSEABLE) && (value instanceof Closeable)) {
     _writeCloseable(jgen, value, _config);
     return;
   }
   boolean closed = false;
   try {
     if (_rootType == null) {
       _serializerProvider(_config).serializeValue(jgen, value);
     } else {
       _serializerProvider(_config).serializeValue(jgen, value, _rootType, _rootSerializer);
     }
     closed = true;
     jgen.close();
   } finally {
     /* won't try to close twice; also, must catch exception (so it
      * will not mask exception that is pending)
      */
     if (!closed) {
       try {
         jgen.close();
       } catch (IOException ioe) {
       }
     }
   }
 }
  private void writeSupportedProperty(
      JsonGenerator jgen,
      String currentVocab,
      ActionInputParameter actionInputParameter,
      String propertyName,
      Property property,
      @SuppressWarnings("unused") Object[] possiblePropertyValues)
      throws IOException {

    jgen.writeStartObject();

    if (actionInputParameter.hasCallValue() || actionInputParameter.hasInputConstraints()) {
      // jgen.writeArrayFieldStart("@type");
      // jgen.writeString("hydra:SupportedProperty");

      jgen.writeStringField(
          JsonLdKeywords.AT_TYPE,
          getPropertyOrClassNameInVocab(
              currentVocab,
              "PropertyValueSpecification",
              LdContextFactory.HTTP_SCHEMA_ORG,
              "schema:"));

      // jgen.writeEndArray();
    }
    jgen.writeStringField("hydra:property", propertyName);

    writePossiblePropertyValues(jgen, currentVocab, actionInputParameter, possiblePropertyValues);

    jgen.writeEndObject();
  }
  @Test
  public void test1() throws IOException {

    MapData ld0 = new MapData();
    ld0.put("Copyright", "\u00A9 2014, David R. Smith. All Rights Reserved");
    ld0.put("License", "http://www.apache.org/licenses/LICENSE-2.0.txt");

    MapData ld1 = new MapData();
    ld1.put("some key", "some data");
    ld1.put("another key", "more data");
    MapDataFormatter format = new MapDataFormatter();
    format.add(ld0);
    format.add(ld1);

    StringWriter writer = new StringWriter();
    JsonFactory f = new JsonFactory();
    JsonGenerator g = null;
    try {
      g = f.createGenerator(writer);
      g.useDefaultPrettyPrinter();
      g.writeStartObject();
      format.format(g, writer);
      g.writeEndObject();
    } finally {
      g.close();
    }

    System.err.println(writer.toString());

    MapIterator iter3 = new MapDataContentsIterator(ld0);
    while (iter3.hasNext()) {
      String label = iter3.next();
      Assert.assertNotNull(iter3.get(label));
    }
  }
 private void writeApplication(JsonGenerator jgen, Application application) throws IOException {
   jgen.writeStartObject();
   jgen.writeStringField("applicationName", application.getName());
   jgen.writeStringField("serviceType", application.getServiceType().getDesc());
   jgen.writeNumberField("code", application.getServiceTypeCode());
   jgen.writeEndObject();
 }
 public static String dumpConfigurationAsJson() {
   ImmutableCollection<String> keys = CONFIGURATION_SECTIONS.keySet();
   ObjectMapper mapper = new ObjectMapper();
   JsonFactory jfactory = mapper.getJsonFactory();
   StringWriter sw = new StringWriter();
   try {
     JsonGenerator gen = jfactory.createJsonGenerator(sw);
     gen.writeStartArray();
     for (String v : keys) {
       String st = dumpConfigurationAsJson(v);
       ObjectMapper op = new ObjectMapper();
       JsonNode p = op.readTree(st);
       Logger.debug("OBJECT:" + p.toString());
       Logger.debug("STRING:" + st);
       // JsonParser jp = jfactory.createJsonParser(st);
       gen.writeTree(p);
     }
     gen.writeEndArray();
     gen.close();
     return sw.toString();
   } catch (Exception e) {
     Logger.error("Cannot generate a json for the configuration", e);
   }
   return "[]";
 } // dumpConfigurationAsJson()
  @Override
  protected void renderMergedOutputModel(
      Map<String, Object> model, HttpServletRequest request, HttpServletResponse response)
      throws Exception {

    OutputStream stream =
        this.updateContentLength ? createTemporaryOutputStream() : response.getOutputStream();

    Object value = filterModel(model);
    JsonGenerator generator =
        this.objectMapper.getJsonFactory().createJsonGenerator(stream, this.encoding);

    // A workaround for JsonGenerators not applying serialization features
    // https://github.com/FasterXML/jackson-databind/issues/12
    if (this.objectMapper.isEnabled(SerializationFeature.INDENT_OUTPUT)) {
      generator.useDefaultPrettyPrinter();
    }

    if (this.prefixJson) {
      generator.writeRaw("{} && ");
    }
    this.objectMapper.writeValue(generator, value);

    if (this.updateContentLength) {
      writeToResponse(response, (ByteArrayOutputStream) stream);
    }
  }
  public void writeServiceDocument(final JsonGenerator gen) throws IOException {
    gen.writeStartObject();

    if (!isODataMetadataNone) {
      final String metadataUri =
          (serviceRoot == null ? "" : serviceRoot.endsWith("/") ? serviceRoot : (serviceRoot + "/"))
              + Constants.METADATA;
      gen.writeObjectField(Constants.JSON_CONTEXT, metadataUri);

      if (metadata != null
          && metadata.getServiceMetadataETagSupport() != null
          && metadata.getServiceMetadataETagSupport().getMetadataETag() != null) {
        gen.writeStringField(
            Constants.JSON_METADATA_ETAG,
            metadata.getServiceMetadataETagSupport().getMetadataETag());
      }
    }

    gen.writeArrayFieldStart(Constants.VALUE);

    final EdmEntityContainer container = metadata.getEdm().getEntityContainer();
    writeEntitySets(gen, container);
    writeFunctionImports(gen, container);
    writeSingletons(gen, container);
  }
  @Override
  public void serialize(IndexInput input, JsonGenerator jg, SerializerProvider sp)
      throws IOException {
    jg.writeStartObject();

    // Riak bug ... explicitly specifying "default" as the type breaks things
    if (!input.getNamespace().getBucketTypeAsString().equals(Namespace.DEFAULT_BUCKET_TYPE)) {
      jg.writeArrayFieldStart("bucket");
      jg.writeString(input.getNamespace().getBucketTypeAsString());
      jg.writeString(input.getNamespace().getBucketNameAsString());
      jg.writeEndArray();
    } else {
      jg.writeStringField("bucket", input.getNamespace().getBucketNameAsString());
    }

    jg.writeStringField("index", input.getIndex());
    IndexInput.IndexCriteria criteria = input.getCriteria();
    if (criteria instanceof IndexInput.MatchCriteria) {
      IndexInput.MatchCriteria<?> match = (IndexInput.MatchCriteria) criteria;
      jg.writeObjectField("key", match.getValue());
    } else if (criteria instanceof IndexInput.RangeCriteria) {
      IndexInput.RangeCriteria range = (IndexInput.RangeCriteria) criteria;
      jg.writeObjectField("start", range.getBegin());
      jg.writeObjectField("end", range.getEnd());
    }
    jg.writeEndObject();
  }
 /**
  * Method that will handle serialization of Date(-like) values, using {@link SerializationConfig}
  * settings to determine expected serialization behavior. Note: date here means "full" date, that
  * is, date AND time, as per Java convention (and not date-only values like in SQL)
  */
 public final void defaultSerializeDateValue(Date date, JsonGenerator gen) throws IOException {
   if (isEnabled(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)) {
     gen.writeNumber(date.getTime());
   } else {
     gen.writeString(_dateFormat().format(date));
   }
 }
  @Test
  public void testCreateGenerator() throws Exception {

    EbeanServer server = Ebean.getDefaultServer();

    StringWriter writer = new StringWriter();
    JsonContext json = server.json();
    JsonGenerator generator = json.createGenerator(writer);

    Customer customer = new Customer();
    customer.setId(1);
    customer.setName("Jim");

    // we can use the generator before and after our json.toJson() call
    // ... confirming we are not closing the generator
    generator.writeStartArray();
    json.toJson(customer, generator, PathProperties.parse("id,name"));
    generator.writeEndArray();
    generator.close();

    String jsonString = writer.toString();
    assertTrue(jsonString, jsonString.startsWith("["));
    assertTrue(jsonString, jsonString.endsWith("]"));
    assertTrue(jsonString, jsonString.contains("{\"id\":1,\"name\":\"Jim\"}"));
  }
  public void jsonSerializeTree(final ObjectMapper mapper, final OutputStream output)
      throws IOException {

    final JsonGenerator generator = mapper.getFactory().createJsonGenerator(output);
    generator.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false);

    walkTree(
        new WalkCallback() {

          private int curDepth = 0;

          @Override
          public void onCurrentNode(
              final int depth, final NodeInterval curNode, final NodeInterval parent) {
            final ItemsNodeInterval node = (ItemsNodeInterval) curNode;
            if (node.isRoot()) {
              return;
            }

            try {
              if (curDepth < depth) {
                generator.writeStartArray();
                curDepth = depth;
              } else if (curDepth > depth) {
                generator.writeEndArray();
                curDepth = depth;
              }
              generator.writeObject(node);
            } catch (IOException e) {
              throw new RuntimeException("Failed to deserialize tree", e);
            }
          }
        });
    generator.close();
  }
Beispiel #17
0
 public String serializeMap(Map<String, T> translator) throws IOException {
   StringWriter stringWriter = new StringWriter();
   JsonGenerator generator = Acela.JSON_FACTORY.createGenerator(stringWriter);
   serializeMap(generator, translator);
   generator.close();
   return stringWriter.toString();
 }
Beispiel #18
0
 protected String writeTree(TreeCodec treeCodec, TreeNode treeNode) throws IOException {
   StringWriter writer = new StringWriter();
   JsonGenerator g = _factory.createGenerator(writer);
   treeCodec.writeTree(g, treeNode);
   g.close();
   return writer.toString();
 }
 /**
  * Method that will handle serialization of Dates used as {@link java.util.Map} keys, based on
  * {@link SerializationFeature#WRITE_DATE_KEYS_AS_TIMESTAMPS} value (and if using textual
  * representation, configured date format)
  */
 public void defaultSerializeDateKey(Date date, JsonGenerator gen) throws IOException {
   if (isEnabled(SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS)) {
     gen.writeFieldName(String.valueOf(date.getTime()));
   } else {
     gen.writeFieldName(_dateFormat().format(date));
   }
 }
  public void testUtf8Issue462() throws Exception {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    IOContext ioc = new IOContext(new BufferRecycler(), bytes, true);
    JsonGenerator gen = new UTF8JsonGenerator(ioc, 0, null, bytes);
    String str = "Natuurlijk is alles gelukt en weer een tevreden klant\uD83D\uDE04";
    int length = 4000 - 38;

    for (int i = 1; i <= length; ++i) {
      gen.writeNumber(1);
    }
    gen.writeString(str);
    gen.flush();
    gen.close();

    // Also verify it's parsable?
    JsonFactory f = new JsonFactory();
    JsonParser p = f.createParser(bytes.toByteArray());
    for (int i = 1; i <= length; ++i) {
      assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken());
      assertEquals(1, p.getIntValue());
    }
    assertToken(JsonToken.VALUE_STRING, p.nextToken());
    assertEquals(str, p.getText());
    assertNull(p.nextToken());
    p.close();
  }
 @Override
 public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider)
     throws IOException, JsonGenerationException {
   if (value instanceof Number) {
     jgen.writeString("0");
   }
   jgen.writeString("");
 }
 /**
  * Method called after an object field has been output, but before the value is output.
  *
  * <p>Default handling (without pretty-printing) will output a single colon to separate the two.
  * Pretty-printer is to output a colon as well, but can surround that with other (white-space)
  * decoration.
  */
 @Override
 public void writeObjectFieldValueSeparator(JsonGenerator jg) throws IOException {
   if (_spacesInObjectEntries) {
     jg.writeRaw(" : ");
   } else {
     jg.writeRaw(':');
   }
 }
 @Override
 public void serialize(Player player, JsonGenerator jgen, SerializerProvider provider)
     throws IOException, JsonProcessingException {
   jgen.writeStartObject();
   writeNumberField(jgen, "id", player.getId());
   writeStringField(jgen, "username", player.getUser().getUsername());
   jgen.writeEndObject();
 }
 @Override
 public void serialize(
     UserStatus userStatus, JsonGenerator jsonGenerator, SerializerProvider serializerProvider)
     throws IOException {
   if (UserStatus.FOLLOWED == userStatus) jsonGenerator.writeNumber(1);
   if (UserStatus.SUSPEND == userStatus) jsonGenerator.writeNumber(2);
   if (UserStatus.UN_FOLLOWED == userStatus) jsonGenerator.writeNumber(4);
 }
 @Override
 public final byte[] serialize(MediaContent content) throws IOException {
   ByteArrayOutputStream baos = outputStream(content);
   JsonGenerator generator = constructGenerator(baos);
   writeMediaContent(generator, content);
   generator.close();
   return baos.toByteArray();
 }
  protected void writeContent(OutputStream stream, Object content) throws IOException {

    JsonGenerator generator = this.objectMapper.getFactory().createGenerator(stream, this.encoding);

    this.objectMapper.writeValue(generator, content);

    generator.flush();
  }
  @Override
  public void serialize(Link link, JsonGenerator jg, SerializerProvider sp)
      throws IOException, JsonProcessingException {

    jg.writeStartObject();
    jg.writeStringField("href", link.getUri().toString());
    jg.writeEndObject();
  }
 /**
  * Method that will handle serialization of Date(-like) values, using {@link SerializationConfig}
  * settings to determine expected serialization behavior. Note: date here means "full" date, that
  * is, date AND time, as per Java convention (and not date-only values like in SQL)
  */
 public final void defaultSerializeDateValue(long timestamp, JsonGenerator gen)
     throws IOException {
   if (isEnabled(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)) {
     gen.writeNumber(timestamp);
   } else {
     gen.writeString(_dateFormat().format(new Date(timestamp)));
   }
 }
 private void writeArray(JsonGenerator jsonGenerator, Iterable<?> value, Deque<Object> objectStack)
     throws IOException {
   jsonGenerator.writeStartArray();
   for (Object item : value) {
     writeFieldValue(jsonGenerator, item, objectStack);
   }
   jsonGenerator.writeEndArray();
 }
Beispiel #30
0
 public static void toJson(Object pojo, FileWriter fw, boolean prettyPrint)
     throws JsonMappingException, JsonGenerationException, IOException {
   JsonGenerator jg = jf.createGenerator(fw);
   if (prettyPrint) {
     jg.useDefaultPrettyPrinter();
   }
   m.writeValue(jg, pojo);
 }