jdereg / json-io

Convert Java to JSON. Convert JSON to Java. Pretty print JSON. Java JSON serializer. Deep copy Java object graphs.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Request for tutorial

williamclocksin opened this issue · comments

I am reading the Javadocs, user guide, and source code including tests, but having trouble writing code to do custom reading and writing of classes. Some example code would help. I am using the new ReadOptions and WriteOptions, and I got a custom ClassReader working, but getting stuck with a ClassFactory that is never called despite being registered. I'm not faulting json-io, it is simply I'm coding by trial and error instead of seeing an example of how to use the API effectively. Is ClassFactory.newInstance() called if there is already a ClassReader read()? Can anybody point me to fuller examples of newInstance() that go beyond the current documentation for ClassFactory? Thanks

More documentation updates are forthcoming.

To get you going, instead of writing a custom reader, it is now recommended to write a custom "Converter." The Converter class from java-util, is used by json-io to "convert types" (instantiate) an object. The Converter converts from one type to another type.

Now think about that, zoomed out, and you will see that Converter deftly plays the role of "external constructor" for classes, which is timely, now that Java 17+ prevents libraries like json-io from reading private fields from classes in other modules.

Now, json-io uses Converter for instantiation. And since you can convert from one type to another, this allows you to create infinite external constructors for a particular class. For example, converting from a long.class to a Date, you are constructing a Date from a long. Taking that to the extreme example, if you add a converter (the Converter API allows you to add in additional conversions), that converts from Map to YouClass.class, this allows json-io to create your class and populate it. The Map is filled with the Object read from the JSON, and then your conversion function can instantiate your particular instance, set the fields on it. This approach eliminates the need for using the ClassReaders.

The ClassReader's are still supported, but if your object is not instantiable by json-io, you will need to write a Factory class to instantiate your class. json-io separates instantiation to the Factory classes, and reading to the customer reader. However, you can use a Converter class to do both in one step, making it much easier to add unknown class types to the serializer.

Lots of document updates have been made to both the GitHub readme (and connected files) and the Javadocs. Please let me know if this is more inline with your expectations.