Serialize Pojos to JSON using new standard javax.json
Asked Answered
P

3

9

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?

Prostitute answered 27/6, 2013 at 13:51 Comment(0)
C
13

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

Compositor answered 27/6, 2013 at 18:55 Comment(4)
Will that JSR be delivered in Java EE7?Prostitute
@NestorHernandezLoli - No, it is not part of Java EE 7 which is already release.Compositor
It's such a pity, Well I will be using Gson, It would be useful to make Gson a JSRProstitute
@NestorHernandezLoli - Hopefully there will be news of the JSON-Binding JSR soon. I will announce it on my "Java XML and JSON Binding" blog (blog.bdoughan.com) as soon as the JSR starts up.Compositor
M
7

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);
Madewell answered 9/5, 2019 at 5:55 Comment(0)
T
1

Maybe it's because this question is almost 5 years old (I didn't check which java release has these classes) but there is a standard way with javax.json.* classes:

JsonObject json = Json.createObjectBuilder()
        .add("key", "value")
        .build();
try(JsonWriter writer = Json.createWriter(outputStream)) {
    writer.write(json);
}
Tocantins answered 6/3, 2018 at 14:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.