URL-Encoding Serializers
The UrlEncodingSerializer class is used to serialize POJOs into URL-Encoding.
When to use it
Use UrlEncodingSerializer to build a query string or a form body from a bean or map: each property becomes a name=value pair joined by &, with values written in UON notation.
For a REST client that posts a form, the client does this for you; use the serializer directly when you build the string yourself.
Example
import java.util.*;
import org.apache.juneau.marshall.urlencoding.*;
public class UrlEncodingSerializerExample {
public static class Person {
public String name = "John Smith";
public int age = 45;
public List<Integer> scores = List.of(1, 2);
}
public static void main(String[] args) throws Exception {
Person person = new Person();
System.out.println(UrlEncodingSerializer.DEFAULT.write(person));
System.out.println(UrlEncodingSerializer.DEFAULT_EXPANDED.write(person));
System.out.println(UrlEncodingSerializer.DEFAULT_PLAINTEXT.write(person));
}
}
The three lines are age=45&name='John+Smith'&scores=@(1,2), age=45&name='John+Smith'&scores=1&scores=2 and age=45&name=John+Smith&scores=1,2.
Options
The following pre-configured serializers are provided for convenience:
| Instance | Output |
|---|---|
UrlEncodingSerializer.DEFAULT | UON-style values, URL-encoded. |
UrlEncodingSerializer.DEFAULT_EXPANDED | Repeats the name for each collection element (scores=1&scores=2) instead of one UON array. |
UrlEncodingSerializer.DEFAULT_PLAINTEXT | Plain values without UON quoting (name=John+Smith). |
UrlEncodingSerializer.DEFAULT_READABLE | One pair per line, for people. |
For anything else, start from the builder's create() method. The settings readers reach for first:
| Builder method | Effect |
|---|---|
expandedParams() | Write each collection element as its own name=value pair. |
paramFormat(...) / paramFormatPlain() | Write values as UON or as plain text. |
ws() | Use indentation and newlines. |
keepNullProperties() | Write bean properties whose value is null. |
trimEmptyCollections() / trimEmptyMaps() | Skip empty collections or maps. |
sortCollections() / sortMaps() | Sort collections or map entries before writing. |
addBeanTypes() | Add _type properties to beans whose runtime type differs from the declared one. |
The class hierarchy for the builder of this serializer is below. Refer to the builder javadocs for the full set of configurable settings.
See also
- URL-Encoding Parsers: the reverse direction.
- URL-Encoding Support
- @UrlEncoding Annotation
- UON Serializers
- Serializers and Parsers