-
Notifications
You must be signed in to change notification settings - Fork 94
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
56 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
package liqp.filters; | ||
|
||
import com.fasterxml.jackson.core.JsonProcessingException; | ||
import com.fasterxml.jackson.databind.ObjectMapper; | ||
import liqp.TemplateContext; | ||
import liqp.TemplateParser; | ||
|
||
public class Json extends Filter { | ||
@Override | ||
public Object apply(Object value, TemplateContext context, Object... params) { | ||
ObjectMapper mapper = context.getParser().mapper; | ||
|
||
try { | ||
return mapper.writeValueAsString(value); | ||
} catch (JsonProcessingException e) { | ||
context.addError(e); | ||
if (context.getErrorMode() == TemplateParser.ErrorMode.STRICT) { | ||
throw new RuntimeException(e.getMessage(), e); | ||
} | ||
return value; | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
package liqp.filters; | ||
|
||
import liqp.Template; | ||
import liqp.TemplateParser; | ||
import org.junit.Test; | ||
|
||
import java.util.HashMap; | ||
|
||
import static org.junit.Assert.*; | ||
|
||
public class JsonTest { | ||
|
||
@Test | ||
public void testWhenStringIsInputShouldBeStringified() { | ||
Template template = TemplateParser.DEFAULT.parse("{{ 'Hello, World!' | json }}"); | ||
String rendered = template.render(); | ||
assertEquals("\"Hello, World!\"", rendered); | ||
} | ||
|
||
@Test | ||
public void testWhenObjectIsInputShouldBeStringified() { | ||
Template template = TemplateParser.DEFAULT.parse("{{ obj | json }}"); | ||
java.util.Map<String, Object> map = new HashMap<>(); | ||
java.util.Map<String, Object> nested = new HashMap<>(); | ||
nested.put("key", "value"); | ||
map.put("obj", nested); | ||
|
||
String rendered = template.render(map); | ||
assertEquals("{\"key\":\"value\"}", rendered); | ||
} | ||
} |