How to convert Play Framework Models into XML and JSON?

前端 未结 3 1135
说谎
说谎 2020-12-14 04:24

Does the Play Framework have a Native or Recommended way of converting Play models into XML/JSON? Something similar to JAXB or Jackson.

3条回答
  •  我在风中等你
    2020-12-14 05:19

    Short answer: Jackson for JSON and JAXB for XML

    Play itself doesn't provide any documentation on marshalling models but it does ship with 3rd party libraries that can do the job.


    JSON:

    The model:

    public class User extends Model {
        public String username;
        public Long   age; 
    
        @JsonIgnore
        public String password; // field won't be marshalled
    }
    

    Marshall it to JSON using jackson's ObjectMapper.writeValueAsString() method.

    import org.codehaus.jackson.map.ObjectMapper;
    //
    ObjectMapper mapper     = new ObjectMapper();
    String       jsonString = mapper.writeValueAsString(country);
    

    JSON Output:

    {
        "username" : "John Smith",
        "age"      : "25"
    }
    

    XML:

    Care must be taken because of how Play generates getters and setters for it's models under the hood. You won't see the getter and setters in the code but they exist at runtime.

    On the model, it's important to set the XmlAccessorType annotation to PROPERTY. This tells JAXB to serialize from the getter/setters and not from the underlying fields.

    @XmlAccessorType(XmlAccessType.PROPERTY)
    

    We also have to add an @XmlRootElement annotation which specifies the name of the root XML node:

    @XmlRootElement(name = "UserRoot")
    

    To omit a field, we must add the @XmlTransient annotation to the getter. Since there is no getter in the source code, we must add one for every field we want to omit.

    @XmlAccessorType(XmlAccessType.PROPERTY)
    public class User extends Model {
        public String username;
        public Long   age;
    
        @JsonIgnore
        public String password;
    
    
        @XmlTransient // This means ignore this property
        public String getPassword() {
            return this.password;
        }
    }
    

    The marshalling is performed by the JAXB classes Marshaller and JAXBContext

    JAXBContext context    = JAXBContext.newInstance(User.class);
    Marshaller  marshaller = context.createMarshaller();
    
    // Use linefeeds and indentation in the outputted XML
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    
    marshaller.marshal(user, System.out);
    

    Output:

    
        John Smith
        25
    
    

    Summary:

    The Play docs on XML and the Play docs on JSON do provide some information on working with json/xml but there doesn't seem to be any Play Docs describing how to do Marshalling. For that we have to look at 3rd Party libraries and documentation.

提交回复
热议问题