Question

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?

Était-ce utile?

La solution

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

Autres conseils

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);

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);
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top