Skip to content

Commit 6353ead

Browse files
Jon Brisbinjbrisbin
authored andcommitted
Added a JsonFormatter to indent JSON output using the new Formatter support introduced by @skuppa in
a90aa7f
1 parent 6c2385b commit 6353ead

File tree

2 files changed

+46
-2
lines changed

2 files changed

+46
-2
lines changed

src/main/java/org/springframework/data/rest/shell/formatter/FormatProvider.java

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,14 +8,15 @@
88
@Component
99
public class FormatProvider {
1010
private final Collection<Formatter> availableFormatter = new ArrayList<Formatter>();
11-
private final NoOpFormatter noOpFormatter = new NoOpFormatter();
11+
private final NoOpFormatter noOpFormatter = new NoOpFormatter();
1212

1313
public FormatProvider() {
1414
availableFormatter.add(new XmlFormatter());
15+
availableFormatter.add(new JsonFormatter());
1516
}
1617

1718
public Formatter getFormatter(String contentType) {
18-
for (Formatter formatter : availableFormatter) {
19+
for(Formatter formatter : availableFormatter) {
1920
if(formatter.isSupported(contentType)) {
2021
return formatter;
2122
}
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package org.springframework.data.rest.shell.formatter;
2+
3+
import java.io.IOException;
4+
import java.util.Arrays;
5+
import java.util.Collection;
6+
import java.util.List;
7+
import java.util.Map;
8+
9+
import org.codehaus.jackson.map.ObjectMapper;
10+
import org.codehaus.jackson.map.SerializationConfig;
11+
import org.springframework.http.converter.HttpMessageNotReadableException;
12+
13+
/**
14+
* @author Jon Brisbin
15+
*/
16+
public class JsonFormatter extends FormatterSupport {
17+
18+
private static final List<String> SUPPORTED = Arrays.asList("json");
19+
private final ObjectMapper mapper = new ObjectMapper();
20+
21+
{
22+
mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true);
23+
}
24+
25+
@Override public Collection<String> getSupportedList() {
26+
return SUPPORTED;
27+
}
28+
29+
@Override public String format(String nonFormattedString) {
30+
Object obj;
31+
try {
32+
if(nonFormattedString.startsWith("[")) {
33+
obj = mapper.readValue(nonFormattedString.getBytes(), List.class);
34+
} else {
35+
obj = mapper.readValue(nonFormattedString.getBytes(), Map.class);
36+
}
37+
return mapper.writeValueAsString(obj);
38+
} catch(IOException e) {
39+
throw new HttpMessageNotReadableException(e.getMessage(), e);
40+
}
41+
}
42+
43+
}

0 commit comments

Comments
 (0)