FreeMarker使用javax.json.JsonObject作为数据模型

时间:2016-05-31 20:59:56

标签: freemarker

我正在测试FreeMarker

Maven 依赖项:

<dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.glassfish</groupId>
        <artifactId>javax.json</artifactId>
        <version>1.0.4</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.freemarker</groupId>
        <artifactId>freemarker</artifactId>
        <version>2.3.23</version>
    </dependency>
</dependencies>

简单课用户

public class User {

    private String firstName;
    private String lastName;
    private String email;

    public User(String firstName, String lastName, String email) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.email = email;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

}

简单的FreeMarker文件( basicJson.ftl ):

Name: ${user.firstName} ${user.lastName}

用于创建配置的类:

import java.io.File;
import java.io.IOException;

import freemarker.template.Configuration;
import freemarker.template.TemplateExceptionHandler;

public class FreemarkerConfigurationFactory {

    public static Configuration newFreemarkerConfiguration() throws IOException {
        Configuration cfg = new Configuration(Configuration.VERSION_2_3_23);
        cfg.setDirectoryForTemplateLoading(new File("./templates/tests/"));
        cfg.setDefaultEncoding("UTF-8");
        cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
        cfg.setLogTemplateExceptions(false);
        return cfg;
    }

}

测试类:

import static org.junit.Assert.assertEquals;

import java.io.ByteArrayOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import javax.json.Json;
import javax.json.JsonObject;

import org.junit.Before;
import org.junit.Test;

import freemarker.template.Configuration;
import freemarker.template.Template;

public class FreemarkerJsonTest {

    private Configuration cfg;
    private ByteArrayOutputStream output;
    private Template template;
    private Writer writer;
    private Map<String, Object> map;

    @Before
    public void setUp() throws Exception {
        cfg =  FreemarkerConfigurationFactory.newFreemarkerConfiguration();
        output = new ByteArrayOutputStream();
        writer = new OutputStreamWriter(output);
        map = new HashMap<>();
    }

    @Test
    public void objectTest() throws Exception {
        User user = new User("Clarice", "Leman", "clarice.leman@domain.com");
        map.put("user", user);
        String outputString = process("basicJson.ftl", map);
        assertEquals("Name: Clarice Leman", outputString);
    }

    @Test
    public void jsonTest() throws Exception {
        JsonObject jsonUser = Json.createObjectBuilder()
            .add("id", 10)
            .add("firstName", "Clarice")
            .add("lastName", "Leman")
            .add("email", "clarice.leman@domain.com")
            .build();

        map.put("user", jsonUser);
        String outputString = process("basicJson.ftl", map);
        assertEquals("Name: Clarice Leman", outputString);
    }

    private String process(String templateName, Object root) throws Exception {
        template = cfg.getTemplate(templateName);
        template.process(root, writer);
        return output.toString();
    }

}

问题是测试“objectTest()”通过但测试“jsonTest()”没有,因为它产生一个字符串:

Name: "Clarice" "Leman"

使用在线FreeMarker模板(http://freemarker-online.kenshoo.com/):

模板:

Name: ${user.firstName} ${user.lastName}

数据模型:

user = {"firstName":"Clarice","lastName":"Leman","email":"clarice.leman@domain.com"}

结果

Name: Clarice Leman

1 个答案:

答案 0 :(得分:2)

您在FreeMarker Online上输入的JSON在传递给FreeMarker之前会被FreeMarker Online转换为List - s和Map - s。整个框的语法特定于该在线服务。因此,如果要显示JSON,则必须将其转换为FreeMarker的默认ObjectWrapper已经理解的内容,或者必须扩展ObjectWrapper以理解javax.json类。 (但是,通常,您将JSON绑定到某些特定于应用程序的类,而那些通常已经使用JavaBeans约定和List - s,默认ObjectWrapper可以理解。)