samedi 12 septembre 2015

How to serialize java objects as field.path = field.value

I have the following model classes:

package com.ab.model;

import java.util.List;

public class Request {

    public Request(String requestType, Body body, List<String> emails) {
        this.requestType = requestType;
        this.body =body;
        this.emails = emails;
    }

    private String requestType;
    private Body body;
    private List<String> emails;

    public String getRequestType() {
        return requestType;
    }

    public void setRequestType(String requestType) {
        this.requestType = requestType;
    }

    public Body getBody() {
        return body;
    }

    public void setBody(Body body) {
        this.body = body;
    }

    public List<String> getEmails() {
        return emails;
    }

    public void setEmails(List<String> emails) {
        this.emails = emails;
    }

}

class Body {

    private String content;
    private List<Header> headers;

    public Body(String content, List<Header> headers) {
        this.content = content;
        this.headers = headers;
    }

    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
    public List<Header> getHeaders() {
        return headers;
    }
    public void setHeaders(List<Header> headers) {
        this.headers = headers;
    }   

}

class Header {

    private String headerName;

    public Header (String headerName) {
        this.headerName = headerName;
    }

    public String getHeaderName() {
        return headerName;
    }

    public void setHeaderName(String headerName) {
        this.headerName = headerName;
    }

}

And the following instance of the Request class:

Request request = new Request(
                "get", 
                new Body("abcdefg", 
                        Arrays.asList(new Header("header_one"))), 
                Arrays.asList("a@a.com", "b@b.com"));

Do you know any library or algorithm that can serialize the request object into the following string?

requestType = "get"
body.content = "abcdefg"
body.headers[0].headerName = "header_one"
emails[0] = "a@a.com"
emails[1] = "b@b.com"

I know I can serialize it as json, xml, etc, but these don't fit my use case. Basically I need a serialization like: field.nestedField.reallyNestedField = "its primitive value"

As a next step, I am planning to read the generated string and generate arbitrary data for each field/nestedField then deserialize it back using PropertyUtils from Apache e.g.:

PropertyUtils.setProperty(requestObject, "requestType", "random type");
PropertyUtils.setProperty(requestObject, "body.content", "random content");
//...

Many thanks! Andrei





Aucun commentaire:

Enregistrer un commentaire