In what way can Java generate a Bean (not just a Map object)--a bean with fields, getters, and setters from a JSON String.
Here's the code I am trying now using ByteBuddy (non-working code/error):
Object contextObject = new ByteBuddy()
.subclass(Object.class)
.defineField("date", String.class, Modifier.PUBLIC)
.defineMethod("getDate", Void.TYPE, Modifier.PUBLIC)
.intercept(FieldAccessor.ofField("date"))
.make()
.load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
.getLoaded()
.newInstance();
BeanUtils.setProperty(contextObject, "date", "August 1, 2017");
However, due to the "wired" natured for ByteBuddy, I am not sure how flexible it can be to generate a dynamic bean from JSON.
Byte Buddy is a generic class generation tool, of course you can define a bean using it. You just need to loop over your properties. Something like the following:
DynamicType.Builder<?> builder = ...
for ( ... ) {
Class<?> type = ...
String name = ...
builder = builder.defineField(name, type, Visibility.PRIVATE)
.defineMethod("get" + name, type, Visibility.PUBLIC)
.intercept(FieldAccessor.ofBeanProperty())
.defineMethod("set" + name, void.class, Visibility.PUBLIC)
.withParameters(type)
.intercept(FieldAccessor.ofBeanProperty());
}
This has become such a common request that I have added a convenience method to the builder API for the next release:
DynamicType.Builder<?> builder = ...
for ( ... ) {
Class<?> type = ...
String name = ...
builder = builder.definedProperty(name, type);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With