users@jsonb-spec.java.net

[jsonb-spec users] Re: Integrating JSON-B with Bean Validation

From: Ehsan Zaery Moghaddam <zaerymoghaddam_at_gmail.com>
Date: Thu, 9 Mar 2017 16:08:25 +0100

Hi Gunnar

Here is a working sample (I tested it):

    public static void main(String[] args) {
        JsonbConfig jsonbConfig = new JsonbConfig();
        jsonbConfig.withAdapters(new BlogAdapter());
        Jsonb jsonb = new
JsonBindingBuilder().withConfig(jsonbConfig).build();

        Blog javaindeed = new Blog("Java Indeed Blog", "
https://www.javaindeed.com");

        String jsonResult = jsonb.toJson(javaindeed);
        System.out.println(jsonResult);

        Blog blog =
jsonb.fromJson("{\"whatever-name\":\"whatever-value\"}", Blog.class);
        System.out.println(blog.getAddress());

    }

And here is the adapter implementation:

public class BlogAdapter implements
javax.json.bind.adapter.JsonbAdapter<Blog, String> {
    @Override
    public String adaptToJson(Blog blog) throws Exception {
        return "Hello from adapter";
    }

    @Override
    public Blog adaptFromJson(String s) throws Exception {
        return new Blog("Adapter provided name", "Adapter provided value");
    }
}

But it's not clear for me how we could use the adapter for this purpose
without having any dependency to CDI. Adapters are being instantiated
normally via reflection.

Ehsan Zaery Moghaddam
Java Developer
Email: zaerymoghaddam_at_gmail.com
<http://ir.linkedin.com/in/zaerymoghaddam>
<http://twitter.com/zaerymoghaddam> <http://github.com/moghaddam>

On Thu, Mar 9, 2017 at 3:40 PM, <gunnar.morling_at_googlemail.com> wrote:

> > What about events - we pushed it back to v >1.0 to see if there
> > is any need
>
> That sounds interesting, I was wondering indeed, too, whether there'd
> be support for listeners somehow.
>
> > - instead of a hard dependency to bean validation?
>
> Note I'm not suggesting to make it a hard dependency, but rather an
> optional one, as done in JPA.
> I.e. BV would only be used if a BV provider is available but of course
> JSON-B would be perfectly usable without it.
>
> For the listener approach to be beneficial - in terms of saving the
> user some work - should there be a ValidationListener defined by the
> spec? Or implementations would provide one (reducing portability)?
>
> I feel the suggested more explicit integration may be easier to use.
> Nevertheless listeners seemed like a good addition.
>
> > Thinking a bit more i think adapters can already play that role if
> you use
> > a JsonbAdapter<A, A>, so do we really need something? Did someone try
> that
> > option?
>
> How would that look like? I just tried
>
> public class ValidationAdapter implements JsonbAdapter<Object,
> Object> { ... }
>
> Jsonb jsonb = JsonbBuilder.create(
> new JsonbConfig()
> .withAdapters( new ValidationAdapter( v ) )
> );
>
> But it wouldn't invoke that adapter during unmarshalling.
>
> --Gunnar
>