Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize Pojos to JSON using new standard javax.json

I like the idea of having a standard for JSON serialization in Java, javax.json is a great step forward you can do an object graph like this:

JsonObject jsonObject3 =
Json.createObjectBuilder()
.add("name", "Ersin")
.add("surname", "Çetinkaya")
.add("age", 25)
.add("address",
      Json.createObjectBuilder()
          .add("city", "Bursa")
          .add("country", "Türkiye")
          .add("zipCode", "33444"))
.add("phones",
              Json.createArrayBuilder()
                  .add("234234242")
                  .add("345345354"))
.build();    

That's it, but how can I serialize a pojo or simple Java object(like a Map) direct to JSON?, something like I do in Gson:

Person person = new Person();
String jsonStr = new Gson().toJson(person);

How can I do this with the new standard API?

like image 363
Nestor Hernandez Loli Avatar asked Jun 27 '13 13:06

Nestor Hernandez Loli


2 Answers

Java API for JSON Processing (JSR-353) does not cover object binding. This will be covered in a separate JSR.

like image 68
bdoughan Avatar answered Sep 18 '22 02:09

bdoughan


See JSR-367, Java API for JSON Binding (JSON-B), a headline feature in Java™ EE 8.

Document: Json Binding 1.0 Users Guide

// Create Jsonb and serialize
Jsonb jsonb = JsonbBuilder.create();
String result = jsonb.toJson(dog);

// Deserialize back
dog = jsonb.fromJson("{name:\"Falco\", age:4, bitable:false}", Dog.class);
like image 36
RJ.Hwang Avatar answered Sep 17 '22 02:09

RJ.Hwang