3

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.

John Little
  • 10,707
  • 19
  • 86
  • 158

1 Answers1

3

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>
Sridhar Sarnobat
  • 25,183
  • 12
  • 93
  • 106
Ahmed HENTETI
  • 1,108
  • 8
  • 18
  • Thanks for the reply. My IDE doesnt find this type, whats the package? javax.json has things like jsonBuilderFactory, but I cant find jsonb or JsonBuilder? – John Little Apr 05 '21 at 20:52
  • I also tried importing from javax, but get "The import javax.json.bind cannot be resolved". Googling this it says you get this with java 7, but I have java 11. Is it not in java 11? – John Little Apr 05 '21 at 20:59
  • Yes, you are right! In fact, it is JavaEE API. I will update my answer – Ahmed HENTETI Apr 05 '21 at 21:00
  • Thanks for the update. Whats "RI"? Do I need jasson? Do I also need org.glassfish javax.json? – John Little Apr 05 '21 at 21:09
  • In fact, in JavaEE we have APIs and Impls. **RI** stands for reference implementation – Ahmed HENTETI Apr 05 '21 at 21:12
  • And as I know, **yasson** is the only implementation of the JSON-B API – Ahmed HENTETI Apr 05 '21 at 21:18
  • Bizarrely when I add "Jsonb jsonb = JsonbBuilder.create(); to any one servlet , all spring servlets stop working, and give: Resource at '/bin/demo/querybuilder' not found: No resource found Cannot serve request to /bin/demo/querybuilder in BundledScriptServlet (/libs/sling/servlet/errorhandler/404.jsp) Request Progress: 0 TIMER_START{Request Processing} 21 COMMENT timer_end format is {,} 43 LOG Method=GET, PathInfo=null Error.log nas nothing (other than the 404), and there are no build errors. – John Little Apr 06 '21 at 07:34