0

I have a Document case class. To Serialize it and deserialize to and from Json text, I defined implicit Reads and Writes object.

If my Document class contains only Int and String, I have no problem. However when I have an Html type value in my Document case class, I have the issue.

It is a nesting serialization and deserialization. I have a problem creating a Reader for Html. Play 2 Html is not a case class. Is that a problem?

Is the following code is right:

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

It does not work. How should I do it? Thanks

Ervinn
  • 1
  • 2

1 Answers1

0

This is how I solved this problem in java (but I guess it is the same in scala): I create a JsonSerializer class to translate a class into a string and then I annote the fields which will be translate into Json with my class.

An exemple to show you how it work for the date:

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);
    }
}

Then I annote the corresponding field with my class:

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 date au format: 08-13-2014

I copied the sources from Loiane Groner.

Moebius
  • 6,242
  • 7
  • 42
  • 54