本文整理了Java中org.apache.juneau.json.JsonSerializer
类的一些代码示例,展示了JsonSerializer
类的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。JsonSerializer
类的具体详情如下:
包路径:org.apache.juneau.json.JsonSerializer
类名称:JsonSerializer
[英]Serializes POJO models to JSON.
Handles Accept
types: application/json, text/json
Produces Content-Type
types: application/json
The conversion is as follows...
The types above are considered "JSON-primitive" object types. Any non-JSON-primitive object types are transformed into JSON-primitive object types through org.apache.juneau.transform.PojoSwap associated through the BeanContextBuilder#pojoSwaps(Class...) method. Several default transforms are provided for transforming Dates, Enums, Iterators, etc...
This serializer provides several serialization options. Typically, one of the predefined DEFAULT serializers will be sufficient. However, custom serializers can be constructed to fine-tune behavior.
The following direct subclasses are provided for convenience:
// Use one of the default serializers to serialize a POJO String json = JsonSerializer.DEFAULT.serialize(someObject); // Create a custom serializer for lax syntax using single quote characters JsonSerializer serializer = JsonSerializer.create().simple().sq().build(); // Clone an existing serializer and modify it to use single-quotes JsonSerializer serializer = JsonSerializer.DEFAULT.builder().sq().build(); // Serialize a POJO to JSON String json = serializer.serialize(someObject);
[中]将POJO模型序列化为JSON。
#####媒体类型
处理Accept
类型:application/json, text/json
生成Content-Type
类型:application/json
#####描述
转换如下。。。
*映射(例如HashMap、TreeMap)被转换为JSON对象。
*集合(例如HashSet、LinkedList)和Java数组被转换为JSON数组。
*字符串转换为JSON字符串。
*数字(例如整型、长型、双精度)转换为JSON数字。
*布尔值转换为JSON布尔值。
*空值转换为JSON空值。
*数组被转换为JSON数组。
*bean被转换为JSON对象。
上述类型被视为“JSON基元”对象类型。任何非JSON基元对象类型都通过org转换为JSON基元对象类型。阿帕奇。朱诺。使改变通过BeanContextBuilder关联的PojoSwap#pojoSwaps(类…)方法为转换日期、枚举、迭代器等提供了几个默认转换。。。
此序列化程序提供多个序列化选项。通常,一个预定义的默认序列化程序就足够了。但是,可以构造自定义序列化程序来微调行为。
#####行为特定子类
为方便起见,提供了以下直接子类:
*SimpleJsonSerializer-默认序列化程序,单引号,简单模式。
*SimpleJSON序列化程序。可读-默认序列化程序,单引号,简单模式,带空格。
#####例如:
//使用默认序列化程序之一序列化POJO字符串json=JsonSerializer。违约序列化(someObject);//使用单引号字符JsonSerializer serializer=JsonSerializer为lax语法创建自定义序列化程序。创建()。简单()。sq()。build();//克隆现有序列化程序并将其修改为使用单引号JsonSerializer serializer=JsonSerializer。违约生成器()。sq()。build();//将POJO序列化为JSON字符串JSON=serializer。序列化(someObject);
代码示例来源:origin: org.apache.juneau/juneau-marshall
/**
* Convenience method for serializing this ObjectList to the specified Writer using the JsonSerializer.DEFAULT
* serializer.
*
* @param w The writer to send the serialized contents of this object.
* @throws IOException If a problem occurred trying to write to the writer.
* @throws SerializeException If a problem occurred trying to convert the output.
*/
public void serializeTo(Writer w) throws IOException, SerializeException {
JsonSerializer.DEFAULT.serialize(this);
}
代码示例来源:origin: org.apache.juneau/juneau-marshall
/**
* Returns the schema serializer based on the settings of this serializer.
*
* <p>
* Note that this method creates a builder initialized to all default settings, whereas {@link #builder()} copies
* the settings of the object called on.
*
* @return The schema serializer.
*/
public JsonSchemaSerializer getSchemaSerializer() {
if (schemaSerializer == null)
schemaSerializer = builder().build(JsonSchemaSerializer.class);
return schemaSerializer;
}
代码示例来源:origin: org.apache.juneau/juneau-marshall
@Override /* Object */
public String toString() {
return SimpleJsonSerializer.DEFAULT.toString(this);
}
}
代码示例来源:origin: org.apache.juneau/juneau-examples-core
String withWhitespace = JsonSerializer.create().ws().build().serialize(aPojo);
String escaped = JsonSerializer.create().escapeSolidus().build().serialize(aPojo);
.create() // Create a JsonSerializerBuilder
.serialize(aPojo); // Create a JsonSerializer
代码示例来源:origin: apache/juneau
@Test
public void testComparison() throws Exception {
List<UrlPathPattern> l = new LinkedList<>();
l.add(new UrlPathPattern("/foo"));
l.add(new UrlPathPattern("/foo/*"));
l.add(new UrlPathPattern("/foo/bar"));
l.add(new UrlPathPattern("/foo/bar/*"));
l.add(new UrlPathPattern("/foo/{id}"));
l.add(new UrlPathPattern("/foo/{id}/*"));
l.add(new UrlPathPattern("/foo/{id}/bar"));
l.add(new UrlPathPattern("/foo/{id}/bar/*"));
Collections.sort(l);
assertEquals("[{patternString:'/foo/bar',vars:[]},{patternString:'/foo/bar/*',vars:[]},{patternString:'/foo/{id}/bar',vars:['id']},{patternString:'/foo/{id}/bar/*',vars:['id']},{patternString:'/foo/{id}',vars:['id']},{patternString:'/foo/{id}/*',vars:['id']},{patternString:'/foo',vars:[]},{patternString:'/foo/*',vars:[]}]", SimpleJsonSerializer.DEFAULT.builder().sortProperties().build().serialize(l));
}
}
代码示例来源:origin: apache/juneau
JsonSerializer serializer = JsonSerializer.create().ssq().addBeanTypes(false).addRootType().build();
assertEquals("{person1:{name:'some name',age:123,addresses:[{street:'street A',city:'city A',state:'state A',zip:12345,isCurrent:true},{street:'street B',city:'city B',state:'state B',zip:12345,isCurrent:false}]}}", serializer.serialize(model.getRootObject()));
serializer = SimpleJsonSerializer.DEFAULT.builder().addBeanTypes().addRootType().build();
p = new Person("some name", 123,
new Address("street A", "city A", "state A", 12345, true),
String s = serializer.serialize(p);
String expectedValue = "{_type:'Person',name:'some name',age:123,addresses:[{street:'street A',city:'city A',state:'state A',zip:12345,isCurrent:true},{street:'street B',city:'city B',state:'state B',zip:12345,isCurrent:false}]}";
assertEquals(expectedValue, s);
s = serializer.serialize(p);
expectedValue = "{_type:'Person',name:'some name',age:123,addresses:[{street:'street A',city:'city A',state:'state A',zip:12345,isCurrent:true},{street:'street B',city:'city B',state:'state B',zip:12345,isCurrent:false}]}";
assertEquals(expectedValue, s);
model.put("addresses/1", new Address("street E", "city E", "state E", 12345, false));
model.put("addresses/2", new Address("street F", "city F", "state F", 12345, false));
serializer = JsonSerializer.create().ssq().build();
s = serializer.serialize(p);
expectedValue = "{name:'some name',age:123,addresses:[{street:'street D',city:'city D',state:'state D',zip:12345,isCurrent:false},{street:'street E',city:'city E',state:'state E',zip:12345,isCurrent:false},{street:'street F',city:'city F',state:'state F',zip:12345,isCurrent:false}]}";
assertEquals(expectedValue, s);
s = serializer.serialize(p);
expectedValue = "{name:'some name',age:123,addresses:[{street:'street D',city:'city D',state:'state D',zip:12345,isCurrent:false},{street:'street F',city:'city F',state:'state F',zip:12345,isCurrent:false}]}";
assertEquals(expectedValue, s);
s = serializer.serialize(p);
expectedValue = "{name:'some name',age:123,addresses:[]}";
assertEquals(expectedValue, s);
代码示例来源:origin: apache/juneau
@Test
public void testRecursion() throws Exception {
JsonSerializerBuilder s = JsonSerializer.create().ssq();
s.build().serialize(r1);
fail("Exception expected!");
} catch (Exception e) {
s.build().serialize(r1);
fail("Exception expected!");
} catch (Exception e) {
assertEquals("{name:'foo',r2:{name:'bar',r3:{name:'baz'}}}", s.build().serialize(r1));
s.build().getSchemaSerializer().serialize(r1);
代码示例来源:origin: apache/juneau
@Test
public void testBeanPropertyProperies() throws Exception {
JsonSerializer s = SimpleJsonSerializer.DEFAULT;
E1 t = new E1();
String r;
r = s.serialize(t);
assertEquals("{x1:{f1:1},x2:{f1:1},x3:[{f1:1}],x4:[{f1:1}],x5:[{f1:1}],x6:[{f1:1}]}", r);
r = s.getSchemaSerializer().serialize(t);
assertTrue(r.indexOf("f2") == -1);
}
代码示例来源:origin: apache/juneau
@Test
public void test() throws Exception {
WriterSerializer s = JsonSerializer.create().ssq().pojoSwaps(EnumerationSwap.class).build();
Vector<String> v = new Vector<>(Arrays.asList(new String[]{"foo","bar","baz"}));
Enumeration<String> e = v.elements();
assertEquals("['foo','bar','baz']", s.serialize(e));
}
}
代码示例来源:origin: org.apache.juneau/juneau-server
/**
* Same as {@link #log(Level, String, Object...)} excepts runs the
* arguments through {@link JsonSerializer#DEFAULT_LAX_READABLE}.
* <p>
* Serialization of arguments do not occur if message is not logged, so
* it's safe to use this method from within debug log statements.
* </p>
*
* <h6 class='topic'>Example:</h6>
* <p class='bcode'>
* logObjects(<jsf>DEBUG</jsf>, <js>"Pojo contents:\n{0}"</js>, myPojo);
* </p>
*
* @param level The log level.
* @param msg The message to log.
* @param args {@link MessageFormat} style arguments in the message.
*/
protected void logObjects(Level level, String msg, Object...args) {
for (int i = 0; i < args.length; i++)
args[i] = JsonSerializer.DEFAULT_LAX_READABLE.toStringObject(args[i]);
log(level, null, msg, args);
}
代码示例来源:origin: org.apache.juneau/juneau-marshall
private String toJson(Object o) throws SerializeException {
if (jsSession == null)
jsSession = ctx.getJsonSerializer().createSession(null);
return jsSession.serializeToString(o);
}
代码示例来源:origin: org.apache.juneau/juneau-marshall
/**
* Constructor.
*
* @param ps Initialize with the specified config property store.
*/
public JsonSchemaGenerator(PropertyStore ps) {
super(ps.builder().set(BEANTRAVERSE_detectRecursions, true).set(BEANTRAVERSE_ignoreRecursions, true).build());
useBeanDefs = getBooleanProperty(JSONSCHEMA_useBeanDefs, false);
allowNestedExamples = getBooleanProperty(JSONSCHEMA_allowNestedExamples, false);
allowNestedDescriptions = getBooleanProperty(JSONSCHEMA_allowNestedDescriptions, false);
beanDefMapper = getInstanceProperty(JSONSCHEMA_beanDefMapper, BeanDefMapper.class, BasicBeanDefMapper.class);
addExamplesTo = TypeCategory.parse(getStringProperty(JSONSCHEMA_addExamplesTo, null));
addDescriptionsTo = TypeCategory.parse(getStringProperty(JSONSCHEMA_addDescriptionsTo, null));
defaultSchemas = getMapProperty(JSONSCHEMA_defaultSchemas, ObjectMap.class);
Set<Pattern> ignoreTypes = new LinkedHashSet<>();
for (String s : split(ps.getProperty(JSONSCHEMA_ignoreTypes, String.class, "")))
ignoreTypes.add(Pattern.compile(s.replace(".", "\\.").replace("*", ".*")));
this.ignoreTypes = ignoreTypes;
jsonSerializer = new JsonSerializer(ps);
}
代码示例来源:origin: org.apache.juneau/juneau-marshall
super(ps, produces, accept);
simpleMode = getBooleanProperty(JSON_simpleMode, false);
escapeSolidus = getBooleanProperty(JSON_escapeSolidus, false);
addBeanTypes = getBooleanProperty(JSON_addBeanTypes, getBooleanProperty(SERIALIZER_addBeanTypes, false));
代码示例来源:origin: apache/juneau
@Test
public void testJson() throws Exception {
JsonSerializer s = JsonSerializer.create().ssq().pojoSwaps(ReaderSwap.Json.class).build();
Reader r;
Map<String,Object> m;
r = new StringReader("{foo:'bar',baz:'quz'}");
m = new HashMap<>();
m.put("X", r);
assertEquals("{X:{foo:'bar',baz:'quz'}}", s.serialize(m));
}
代码示例来源:origin: apache/juneau
@Test
public void testSubTypeWithGenerics() throws Exception {
JsonSerializer s = JsonSerializer.DEFAULT.builder().addBeanTypes().addRootType().build();
C1 c1 = C3.create();
String r = s.serialize(c1);
assertEquals("{\"_type\":\"C3\",\"f1\":{\"f2\":\"f2\",\"f3\":3}}", r);
}
代码示例来源:origin: apache/juneau
@Test
public void test() throws Exception {
WriterSerializer s = JsonSerializer.create().ssq().pojoSwaps(IteratorSwap.class).build();
// Iterators
List<String> l = new ArrayList<>(Arrays.asList(new String[]{"foo","bar","baz"}));
Iterator<String> i = l.iterator();
assertEquals("['foo','bar','baz']", s.serialize(i));
}
}
代码示例来源:origin: apache/juneau
/**
* Same as {@link #log(Level, String, Object...)} excepts runs the arguments through {@link JsonSerializer#DEFAULT_READABLE}.
*
* <p>
* Serialization of arguments do not occur if message is not logged, so it's safe to use this method from within
* debug log statements.
*
* <h5 class='section'>Example:</h5>
* <p class='bcode w800'>
* logObjects(<jsf>DEBUG</jsf>, <js>"Pojo contents:\n{0}"</js>, myPojo);
* </p>
*
* @param level The log level.
* @param msg The message to log.
* @param args Optional {@link MessageFormat}-style arguments.
*/
@Override /* RestLogger */
public void logObjects(Level level, String msg, Object...args) {
for (int i = 0; i < args.length; i++)
args[i] = SimpleJsonSerializer.DEFAULT_READABLE.toStringObject(args[i]);
log(level, null, msg, args);
}
代码示例来源:origin: apache/juneau
private String toJson(Object o) throws SerializeException {
if (jsSession == null)
jsSession = ctx.getJsonSerializer().createSession(null);
return jsSession.serializeToString(o);
}
代码示例来源:origin: apache/juneau
/**
* Constructor.
*
* @param ps Initialize with the specified config property store.
*/
public JsonSchemaGenerator(PropertyStore ps) {
super(ps.builder().set(BEANTRAVERSE_detectRecursions, true).set(BEANTRAVERSE_ignoreRecursions, true).build());
useBeanDefs = getBooleanProperty(JSONSCHEMA_useBeanDefs, false);
allowNestedExamples = getBooleanProperty(JSONSCHEMA_allowNestedExamples, false);
allowNestedDescriptions = getBooleanProperty(JSONSCHEMA_allowNestedDescriptions, false);
beanDefMapper = getInstanceProperty(JSONSCHEMA_beanDefMapper, BeanDefMapper.class, BasicBeanDefMapper.class);
addExamplesTo = TypeCategory.parse(getStringProperty(JSONSCHEMA_addExamplesTo, null));
addDescriptionsTo = TypeCategory.parse(getStringProperty(JSONSCHEMA_addDescriptionsTo, null));
defaultSchemas = getMapProperty(JSONSCHEMA_defaultSchemas, ObjectMap.class);
Set<Pattern> ignoreTypes = new LinkedHashSet<>();
for (String s : split(ps.getProperty(JSONSCHEMA_ignoreTypes, String.class, "")))
ignoreTypes.add(Pattern.compile(s.replace(".", "\\.").replace("*", ".*")));
this.ignoreTypes = ignoreTypes;
jsonSerializer = new JsonSerializer(ps);
}
代码示例来源:origin: apache/juneau
super(ps, produces, accept);
simpleMode = getBooleanProperty(JSON_simpleMode, false);
escapeSolidus = getBooleanProperty(JSON_escapeSolidus, false);
addBeanTypes = getBooleanProperty(JSON_addBeanTypes, getBooleanProperty(SERIALIZER_addBeanTypes, false));
内容来源于网络,如有侵权,请联系作者删除!