0

我有一个文档案例类。为了对其进行序列化并在 Json 文本中反序列化,我定义了隐式 Reads 和 Writes 对象。

如果我的 Document 类只包含 Int 和 String,我没有问题。但是,当我的 Document case 类中有 Html 类型值时,我遇到了问题。

它是一种嵌套的序列化和反序列化。我在为 Html 创建阅读器时遇到问题。Play 2 Html 不是案例类。那是问题吗?

下面的代码是否正确:

implicit object HtmlReads extends play.api.libs.json.Reads[Html] {
       def reads(json: JsValue) = Html (
           (json \ "text").as[String] 
        )
}

这没用。我该怎么做?谢谢

4

1 回答 1

0

这就是我在java中解决这个问题的方法(但我想在scala中是一样的):我创建了一个JsonSerializer类来将一个类翻译成一个字符串,然后我注释了将用我的类翻译成Json的字段。

一个向您展示日期如何工作的示例:

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.stereotype.Component;

/**
 * Used to serialize Java.util.Date, which is not a common JSON
 * type, so we have to create a custom serialize method;.
 *
 * @author Loiane Groner
 */
@Component
public class JsonDateSerializer extends JsonSerializer<Date>{

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy");

    @Override
    public void serialize(Date date, JsonGenerator gen, SerializerProvider provider)
            throws IOException, JsonProcessingException {
        String formattedDate = dateFormat.format(date);
        gen.writeString(formattedDate);
    }
}

然后我用我的班级注释相应的字段:

public class MyClass
{
    @Formats.DateTime(pattern="dd/MM/yyyy")
    @JsonSerialize(using=JsonDateSerializer.class)
    public Date     myDate;
}

Ainsi, lorsque j'utilise mapper.writeValueAsString(lst), j'obtiens des 日期 au 格式:08-13-2014

我从Loiane Groner复制了来源。

于 2014-08-07T14:25:11.853 回答