John Little
John Little

Reputation: 12433

Is there a java 11 native way to convert json to an object?

This question: How to parse JSON in Java Has several answers which require including 3rd party libraries, including GSON, org.json and Jackson.

I am using Adobe AEM, which is notoriously intolerant of including 3rd party libraries, so am trying to do the REST API calling with standard Java 11. java 11 has the HTTPClient classes, which will give me JSON from the response.

Now I need to convert Json into the required java object.

E.g. I have a Person class with name and age fields, and want to get a Person object from something like {"name":"bob", "age":12}

I will also need something to convert a Java object into Json.

Any suggestions?

There is something called JsonObject in java 7, but I have not been able to find any examples which show this conversion.

Upvotes: 3

Views: 6400

Answers (1)

Ahmed HENTETI
Ahmed HENTETI

Reputation: 1128

You can use JsonB which was introduced in JavaEE 8

import javax.json.bind.Jsonb;

Jsonb jsonb = JsonbBuilder.create();
Person person = jsonb.fromJson(personString, Person.class);

If you use maven, here is the dependencies to add

<!-- JSON-B API -->
<dependency>
  <groupId>javax.json.bind</groupId>
  <artifactId>javax.json.bind-api</artifactId>
  <version>1.0</version>
</dependency>

<!-- JSON-B RI -->
<dependency>
  <groupId>org.eclipse</groupId>
  <artifactId>yasson</artifactId>
  <version>1.0</version>
  <scope>runtime</scope>
</dependency>

Upvotes: 3

Related Questions