protected void writeObjectToJson(HttpServletResponse resp,Object obj) throws ServletException, IOException{ resp.setHeader("Access-Control-Allow-Origin", "*"); resp.setContentType("text/json"); resp.setCharacterEncoding("UTF-8"); ObjectMapper mapper=new ObjectMapper(); mapper.setSerializationInclusion(Inclusion.NON_NULL); mapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS,false); mapper.setDateFormat(new SimpleDateFormat(Configure.getDateFormat())); OutputStream out = resp.getOutputStream(); try { mapper.writeValue(out, obj); } finally { out.flush(); out.close(); } }
private void configureFeature(Object feature, boolean enabled) { if (feature instanceof JsonParser.Feature) { this.objectMapper.configure((JsonParser.Feature) feature, enabled); } else if (feature instanceof JsonGenerator.Feature) { this.objectMapper.configure((JsonGenerator.Feature) feature, enabled); } else if (feature instanceof SerializationConfig.Feature) { this.objectMapper.configure((SerializationConfig.Feature) feature, enabled); } else if (feature instanceof DeserializationConfig.Feature) { this.objectMapper.configure((DeserializationConfig.Feature) feature, enabled); } else { throw new IllegalArgumentException("Unknown feature class: " + feature.getClass().getName()); } }
@Override protected void writeInternal(Object object, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { JsonEncoding encoding = getJsonEncoding(outputMessage.getHeaders().getContentType()); JsonGenerator jsonGenerator = this.objectMapper.getJsonFactory().createJsonGenerator(outputMessage.getBody(), encoding); // A workaround for JsonGenerators not applying serialization features // https://github.com/FasterXML/jackson-databind/issues/12 if (this.objectMapper.getSerializationConfig().isEnabled(SerializationConfig.Feature.INDENT_OUTPUT)) { jsonGenerator.useDefaultPrettyPrinter(); } try { if (this.jsonPrefix != null) { jsonGenerator.writeRaw(this.jsonPrefix); } this.objectMapper.writeValue(jsonGenerator, object); } catch (JsonProcessingException ex) { throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex); } }
public JsonObjectMapperWriter(OutputStream output, boolean prettyPrint) throws IOException { ObjectMapper mapper = new ObjectMapper(); mapper.configure( SerializationConfig.Feature.CAN_OVERRIDE_ACCESS_MODIFIERS, true); // define a module SimpleModule module = new SimpleModule("Default Serializer", new Version(0, 1, 1, "FINAL")); // add various serializers to the module // add default (all-pass) serializer for all rumen specific data types module.addSerializer(DataType.class, new DefaultRumenSerializer()); // add a serializer to use object.toString() while serializing module.addSerializer(ID.class, new ObjectStringSerializer<ID>()); // register the module with the object-mapper mapper.registerModule(module); mapper.getJsonFactory(); writer = mapper.getJsonFactory().createJsonGenerator( output, JsonEncoding.UTF8); if (prettyPrint) { writer.useDefaultPrettyPrinter(); } }
private void write(DataOutput out) throws IOException { // This is just a JSON experiment System.out.println("Dumping the StatePool's in JSON format."); ObjectMapper outMapper = new ObjectMapper(); outMapper.configure( SerializationConfig.Feature.CAN_OVERRIDE_ACCESS_MODIFIERS, true); // define a module SimpleModule module = new SimpleModule("State Serializer", new Version(0, 1, 1, "FINAL")); // add the state serializer //module.addSerializer(State.class, new StateSerializer()); // register the module with the object-mapper outMapper.registerModule(module); JsonFactory outFactory = outMapper.getJsonFactory(); JsonGenerator jGen = outFactory.createJsonGenerator((DataOutputStream)out, JsonEncoding.UTF8); jGen.useDefaultPrettyPrinter(); jGen.writeObject(this); jGen.close(); }
protected void writeObjectToJson(HttpServletResponse resp,Object obj) throws ServletException, IOException{ resp.setHeader("Access-Control-Allow-Origin", "*"); resp.setContentType("text/json"); resp.setCharacterEncoding("UTF-8"); ObjectMapper mapper=new ObjectMapper(); mapper.setSerializationInclusion(Inclusion.NON_NULL); mapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS,false); mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")); OutputStream out = resp.getOutputStream(); try { mapper.writeValue(out, obj); } finally { out.flush(); out.close(); } }
/** * {@inheritDoc} */ public CustomObjectMapper() { super(); this.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); this.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false); this.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false); this.setSerializationInclusion(JsonSerialize.Inclusion.NON_DEFAULT); this.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL); this.setSerializationInclusion(JsonSerialize.Inclusion.NON_EMPTY); final AnnotationIntrospector introspector = new JaxbAnnotationIntrospector(); // make deserializer use JAXB annotations (only) this.setAnnotationIntrospector(introspector); // TODO leverage NamingStrategy to make reponse attributes more Java-like //this.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES); }
@Override public SchemaType load(ApplicationConfiguration applicationConfiguration, SchemaType schemaType) throws Exception { log.info(" load() "); Meta meta = new Meta(); meta.setLocation(applicationConfiguration.getBaseEndpoint() + "/scim/v2/Schemas/" + schemaType.getId()); meta.setResourceType("Schema"); schemaType.setMeta(meta); // Use serializer to walk the class structure ObjectMapper mapper = new ObjectMapper(); mapper.disable(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS); SimpleModule userCoreLoadingStrategyModule = new SimpleModule("UserCoreLoadingStrategyModule", new Version(1, 0, 0, "")); SchemaTypeUserSerializer serializer = new SchemaTypeUserSerializer(); serializer.setSchemaType(schemaType); userCoreLoadingStrategyModule.addSerializer(User.class, serializer); mapper.registerModule(userCoreLoadingStrategyModule); mapper.writeValueAsString(createDummyUser()); return serializer.getSchemaType(); }
@Override public SchemaType load(ApplicationConfiguration applicationConfiguration, SchemaType schemaType) throws Exception { log.info(" load() "); Meta meta = new Meta(); meta.setLocation(applicationConfiguration.getBaseEndpoint() + "/scim/v2/Schemas/" + schemaType.getId()); meta.setResourceType("Schema"); schemaType.setMeta(meta); // Use serializer to walk the class structure ObjectMapper mapper = new ObjectMapper(); mapper.disable(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS); SimpleModule groupCoreLoadingStrategyModule = new SimpleModule("GroupCoreLoadingStrategyModule", new Version(1, 0, 0, "")); SchemaTypeGroupSerializer serializer = new SchemaTypeGroupSerializer(); serializer.setSchemaType(schemaType); groupCoreLoadingStrategyModule.addSerializer(Group.class, serializer); mapper.registerModule(groupCoreLoadingStrategyModule); mapper.writeValueAsString(createDummyGroup()); return serializer.getSchemaType(); }
@Override public SchemaType load(ApplicationConfiguration applicationConfiguration, SchemaType schemaType) throws Exception { log.info(" load() "); Meta meta = new Meta(); meta.setLocation(applicationConfiguration.getBaseEndpoint() + "/scim/v2/Schemas/" + schemaType.getId()); meta.setResourceType("Schema"); schemaType.setMeta(meta); // Use serializer to walk the class structure ObjectMapper mapper = new ObjectMapper(); mapper.disable(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS); SimpleModule userCoreLoadingStrategyModule = new SimpleModule("FidoDeviceCoreLoadingStrategyModule", new Version(1, 0, 0, "")); SchemaTypeFidoDeviceSerializer serializer = new SchemaTypeFidoDeviceSerializer(); serializer.setSchemaType(schemaType); userCoreLoadingStrategyModule.addSerializer(FidoDevice.class, serializer); mapper.registerModule(userCoreLoadingStrategyModule); mapper.writeValueAsString(createDummyFidoDevice()); return serializer.getSchemaType(); }
public JsonModelSerializer(boolean doNullValues, Class<T> serializedType) { super(); objectMapper = new ObjectMapper(); AnnotationIntrospector introspector = new JaxbAnnotationIntrospector(); // make serializer use JAXB annotations (only) SerializationConfig sc = objectMapper.getSerializationConfig().withAnnotationIntrospector(introspector); sc.with(SerializationConfig.Feature.INDENT_OUTPUT); if (!doNullValues) { sc.without(SerializationConfig.Feature.WRITE_NULL_MAP_VALUES); sc.without(SerializationConfig.Feature.WRITE_EMPTY_JSON_ARRAYS); sc = sc.withSerializationInclusion(Inclusion.NON_EMPTY); } objectMapper.setSerializationConfig(sc); // if (!doNullValues) { // objectMapper.setSerializationInclusion(Inclusion.NON_EMPTY); // } }
/** * Open a JSON output file * The file output may be derived from many input sources * * @param name * @param string * @throws XMLStreamException * @throws IOException */ public void open(File file) throws XMLStreamException, IOException { // Mapped convention JsonFactory f = new JsonFactory(); try { generator = f.createJsonGenerator(new FileWriter(file)); ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true); generator.setCodec(mapper); generator.useDefaultPrettyPrinter(); rootNode = mapper.createObjectNode(); rootNode.put("name", "odfestyles"); rootArray = rootNode.putArray(CHILDREN_TAG); } catch (JsonGenerationException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
public void open(File file) throws XMLStreamException, IOException { // Mapped convention JsonFactory f = new JsonFactory(); try { generator = f.createJsonGenerator(new FileWriter(file)); ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true); generator.setCodec(mapper); generator.useDefaultPrettyPrinter(); rootNode = mapper.createObjectNode(); rootNode.put("name", "odfpaths"); rootArray = rootNode.putArray(CHILDREN_TAG); } catch (JsonGenerationException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
private String getPostSummary(Object o) { String s = ""; ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true); if (o != null) { try { if (o instanceof ImportSummaries) s += mapper.writeValueAsString(mapper.readTree(mapper.writeValueAsString((ImportSummaries) o))); else if (o instanceof DHISImportSummary) s += mapper.writeValueAsString((DHISImportSummary) o); } catch (IOException e) { e.printStackTrace(); } } return s; }
public String getJson(String objName, Object obj) { // List<SimpleClassBasedVisibility> visibilities = getPropertyGroupBasedClassBasedVisibilities(product); // if (visibilities == null || visibilities.size() == 0) { // return null; // } // CustomVisibilityChecker visibilityChecker = new CustomVisibilityChecker(visibilities); // ObjectWriter objectMapper = createObjectMapper(visibilityChecker); ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false); String ret = getJson(objName, obj, mapper.writer()); return ret; }
/** * Create a json file containing the quality model received. * @param p quality model to parse * @return json file * @throws IOException exception */ public File createJsonFile(QModel p) throws IOException { ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false); mapper.configure(SerializationConfig.Feature.USE_ANNOTATIONS, true); mapper.configure(SerializationConfig.Feature.AUTO_DETECT_GETTERS, true); mapper.enable(SerializationConfig.Feature.INDENT_OUTPUT); file = new File(p.getName()+".json"); // write JSON to a file mapper.writeValue(file, p); return file; }
private String buildJson(Object object) { ObjectMapper mapper = new ObjectMapper(); SerializationConfig serializationConfig = mapper.getSerializationConfig(); serializationConfig = serializationConfig.withSerializationInclusion(JsonSerialize.Inclusion.NON_NULL); AnnotationIntrospector introspector = new JaxbAnnotationIntrospector(); mapper.setSerializationConfig(serializationConfig); mapper.setAnnotationIntrospector(introspector); try { return mapper.writeValueAsString(object); } catch (IOException e) { log.warn("Can't marshal search criteria."); throw new RuntimeException("Failed inFolder build criteria json.", e); } }
public static ObjectMapper createFieldsMapper() { ObjectMapper mapper = new ObjectMapper(); // limit to fields only mapper.enable(SerializationConfig.Feature.AUTO_DETECT_FIELDS); mapper.enable(DeserializationConfig.Feature.AUTO_DETECT_FIELDS); mapper.disable(SerializationConfig.Feature.AUTO_DETECT_GETTERS); mapper.disable(SerializationConfig.Feature.AUTO_DETECT_IS_GETTERS); mapper.disable(DeserializationConfig.Feature.AUTO_DETECT_SETTERS); mapper.disable(DeserializationConfig.Feature.AUTO_DETECT_CREATORS); // general configuration mapper.setSerializationInclusion(Inclusion.NON_NULL); mapper.enable(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY); // json.disable(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES); return mapper; }
private String getFriendlyError(Object record, boolean insert) { try { MockStatement stmt = new MockStatement(); if(insert) { prepareInsertParms(stmt, record); } else { prepareUpdateParms(stmt, record); } String msg = String.format("Error upserting record into [%s] using [%s]\n", tableName, driver.name()); msg += (insert ? insertQuery : updateQuery) + "\n"; msg += new ObjectMapper().enable(SerializationConfig.Feature.INDENT_OUTPUT).writeValueAsString(stmt.getParms()); return msg; } catch (Exception ex) { throw new RuntimeException("Error getting error!", ex); } }
@Test public void testBooleanSetters() { factory.setAutoDetectFields(false); factory.setAutoDetectGettersSetters(false); factory.setFailOnEmptyBeans(false); factory.setIndentOutput(true); factory.afterPropertiesSet(); ObjectMapper objectMapper = factory.getObject(); SerializationConfig serializeConfig = objectMapper.getSerializationConfig(); DeserializationConfig deserializeConfig = objectMapper.getDeserializationConfig(); assertFalse(serializeConfig.isEnabled(SerializationConfig.Feature.AUTO_DETECT_FIELDS)); assertFalse(deserializeConfig.isEnabled(DeserializationConfig.Feature.AUTO_DETECT_FIELDS)); assertFalse(serializeConfig.isEnabled(SerializationConfig.Feature.AUTO_DETECT_GETTERS)); assertFalse(deserializeConfig.isEnabled(DeserializationConfig.Feature.AUTO_DETECT_SETTERS)); assertFalse(serializeConfig.isEnabled(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS)); assertTrue(serializeConfig.isEnabled(SerializationConfig.Feature.INDENT_OUTPUT)); }
public JacksonContextResolver() throws Exception { this.mapper = new ObjectMapper() .setDefaultTyping(new OvirtTypeResolverBuilder()) .configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false) .configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false) .configure(DeserializationConfig.Feature.FAIL_ON_NULL_FOR_PRIMITIVES, false) .configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); mapper.setVisibilityChecker(mapper.getSerializationConfig().getDefaultVisibilityChecker() .withFieldVisibility(JsonAutoDetect.Visibility.NON_PRIVATE) .withGetterVisibility(JsonAutoDetect.Visibility.NONE) .withSetterVisibility(JsonAutoDetect.Visibility.NONE) .withCreatorVisibility(JsonAutoDetect.Visibility.DEFAULT)); mapper.registerModule(new OvirtSdkEnhancer()); }
@Override public byte[] serialize(T data) throws PropertyStoreException { ObjectMapper mapper = new ObjectMapper(); SerializationConfig serializationConfig = mapper.getSerializationConfig(); serializationConfig.set(SerializationConfig.Feature.INDENT_OUTPUT, true); serializationConfig.set(SerializationConfig.Feature.AUTO_DETECT_FIELDS, true); serializationConfig.set(SerializationConfig.Feature.CAN_OVERRIDE_ACCESS_MODIFIERS, true); StringWriter sw = new StringWriter(); try { mapper.writeValue(sw, data); if (sw.toString().getBytes().length > ZNRecord.SIZE_LIMIT) { throw new HelixException("Data size larger than 1M. Write empty string to zk."); } return sw.toString().getBytes(); } catch (Exception e) { LOG.error("Error during serialization of data (first 1k): " + sw.toString().substring(0, 1024), e); } return new byte[] {}; }
protected BeanPropertyWriter _constructWriter(SerializationConfig paramSerializationConfig, TypeBindings paramTypeBindings, PropertyBuilder paramPropertyBuilder, boolean paramBoolean, String paramString, AnnotatedMember paramAnnotatedMember) throws JsonMappingException { if (paramSerializationConfig.isEnabled(SerializationConfig.Feature.CAN_OVERRIDE_ACCESS_MODIFIERS)) paramAnnotatedMember.fixAccess(); JavaType localJavaType = paramAnnotatedMember.getType(paramTypeBindings); BeanProperty.Std localStd = new BeanProperty.Std(paramString, localJavaType, paramPropertyBuilder.getClassAnnotations(), paramAnnotatedMember); JsonSerializer localJsonSerializer = findSerializerFromAnnotation(paramSerializationConfig, paramAnnotatedMember, localStd); boolean bool = ClassUtil.isCollectionMapOrArray(localJavaType.getRawClass()); TypeSerializer localTypeSerializer = null; if (bool) localTypeSerializer = findPropertyContentTypeSerializer(localJavaType, paramSerializationConfig, paramAnnotatedMember, localStd); BeanPropertyWriter localBeanPropertyWriter = paramPropertyBuilder.buildWriter(paramString, localJavaType, localJsonSerializer, findPropertyTypeSerializer(localJavaType, paramSerializationConfig, paramAnnotatedMember, localStd), localTypeSerializer, paramAnnotatedMember, paramBoolean); localBeanPropertyWriter.setViews(paramSerializationConfig.getAnnotationIntrospector().findSerializationViews(paramAnnotatedMember)); return localBeanPropertyWriter; }
protected List<BeanPropertyWriter> filterBeanProperties(SerializationConfig paramSerializationConfig, BasicBeanDescription paramBasicBeanDescription, List<BeanPropertyWriter> paramList) { String[] arrayOfString = paramSerializationConfig.getAnnotationIntrospector().findPropertiesToIgnore(paramBasicBeanDescription.getClassInfo()); if ((arrayOfString != null) && (arrayOfString.length > 0)) { HashSet localHashSet = ArrayBuilders.arrayToSet(arrayOfString); Iterator localIterator = paramList.iterator(); while (localIterator.hasNext()) { if (!localHashSet.contains(((BeanPropertyWriter)localIterator.next()).getName())) continue; localIterator.remove(); } } return paramList; }
public JsonSerializer<Object> findBeanSerializer(SerializationConfig paramSerializationConfig, JavaType paramJavaType, BasicBeanDescription paramBasicBeanDescription, BeanProperty paramBeanProperty) throws JsonMappingException { JsonSerializer localJsonSerializer; if (!isPotentialBeanType(paramJavaType.getRawClass())) localJsonSerializer = null; while (true) { return localJsonSerializer; localJsonSerializer = constructBeanSerializer(paramSerializationConfig, paramBasicBeanDescription, paramBeanProperty); if (!this._factoryConfig.hasSerializerModifiers()) continue; Iterator localIterator = this._factoryConfig.serializerModifiers().iterator(); while (localIterator.hasNext()) localJsonSerializer = ((BeanSerializerModifier)localIterator.next()).modifySerializer(paramSerializationConfig, paramBasicBeanDescription, localJsonSerializer); } }
protected <T extends AnnotatedMember> void removeIgnorableTypes(SerializationConfig paramSerializationConfig, BasicBeanDescription paramBasicBeanDescription, Map<String, T> paramMap) { if (paramMap.isEmpty()); while (true) { return; AnnotationIntrospector localAnnotationIntrospector = paramSerializationConfig.getAnnotationIntrospector(); Iterator localIterator = paramMap.entrySet().iterator(); HashMap localHashMap = new HashMap(); while (localIterator.hasNext()) { Class localClass = ((AnnotatedMember)((Map.Entry)localIterator.next()).getValue()).getRawType(); Boolean localBoolean = (Boolean)localHashMap.get(localClass); if (localBoolean == null) { localBoolean = localAnnotationIntrospector.isIgnorableType(((BasicBeanDescription)paramSerializationConfig.introspectClassAnnotations(localClass)).getClassInfo()); if (localBoolean == null) localBoolean = Boolean.FALSE; localHashMap.put(localClass, localBoolean); } if (!localBoolean.booleanValue()) continue; localIterator.remove(); } } }