Skip to content

Instantly share code, notes, and snippets.

@deverton
Created December 2, 2013 02:22
Show Gist options
  • Save deverton/7743979 to your computer and use it in GitHub Desktop.
Save deverton/7743979 to your computer and use it in GitHub Desktop.
Customising Jackson to use new lines between root objects and also customise the serialization of a list. Useful when talking to Elasticsearch _msearch endpoint.
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.util.MinimalPrettyPrinter;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MgetDemo {
public static void main(final String... args) throws Exception {
final ObjectMapper mapper = new ObjectMapper();
final Mget mget = new Mget();
mget.add("inventory", "property", new ArrayList<>(Arrays.asList("1", "2", "3")));
mget.add("inventory", "offer", new ArrayList<>(Arrays.asList("1", "2", "3")));
mapper.writer(new MinimalPrettyPrinter("\n")).writeValue(System.out, mget);
}
@JsonSerialize(using = MgetSerializer.class)
public static class Mget {
public static class Item {
@JsonProperty("_index")
private final String index;
@JsonProperty("_type")
private final String type;
@JsonProperty("_id")
private final String id;
public Item(final String index, final String type, final String id) {
this.index = index;
this.type = type;
this.id = id;
}
}
public final List<Item> items = new ArrayList<>();
public void add(final String index, final String type, final Iterable<String> ids) {
for (String id : ids) {
add(new Item(index, type, id));
}
}
public void add(final Item item) {
items.add(item);
}
}
public static class MgetSerializer extends JsonSerializer<Mget> {
@Override
public boolean isEmpty(final Mget value) {
return value.items.isEmpty();
}
@Override
public Class<Mget> handledType() {
return Mget.class;
}
@Override
public void serialize(final Mget value, final JsonGenerator jgen, final SerializerProvider provider) throws IOException, JsonProcessingException {
for (Mget.Item item : value.items) {
jgen.writeObject(item);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment