Let's say I have the following java class:
public class Person {
private Long id;
private Long deptId;
private String name;
private PhoneNumber workPhone;
// getters and setters follow ...
}
I would like to have the ability to add json attributes that don't exist. I was thinking something like the following:
String jsonSample = new JSONSerializer().prettyPrint(true)
.synthesize("path", new PathPropertySynthesizer())
.serialize(personInstance);
Where the path synthesizer manipulates the person json adding a path attribute such as the following:
{
"id":19,
"deptId":99,
"name":"Matt",
"workPhone": {
"areaCode":212,
"prefix":867,
"suffix":5309
},
"path":"http://example.com/people/99/19"
}
The synthesizer interface would be very similar to transformers/factories. The only real difference would be we need a mechanism to trigger the synthesizers during reflection traversal
You'd have to come up with a reason you couldn't do this with Transfomers. Essentially you are asking for exactly what Transformers already give you. Transfers essentially let you write the JSON for a given path or object. So adding path would be trivial inside a Transformer. You could even write a generic Transformer that performed default serialization of a Bean, then added zero or more additions quite easily. So Synthesizer would implement Transformer and you could do exactly what you describe. This generic implementation might be of interest to the library as a higher level concept than Transfomers.
can you demonstrate how to use transformers to create json fields that are not in the original source object? It seems to me you would have to have a field called path on your java class before the transformer could ever be registered for it.
You don't register it on the object that doesn't exit. You register it on the object you want to put the field within. There are some examples in the code base already. I think BasicDateTransfomer, DateTransformer, and I thought there was another DateTransformer that would break fields into an object with year, month, day, hour, minute, second as fields under that object. That one would be the best to look at but I can't recall the name.
This is essentially what Transformers gives you the ability to do already, and in fact you could build a simple reusable synthesizer yourself using Transformers as a base. This is not going to be added as you have all the tools today to do this.