View Javadoc
1   /*
2    * #%L
3    * wcm.io
4    * %%
5    * Copyright (C) 2023 wcm.io
6    * %%
7    * Licensed under the Apache License, Version 2.0 (the "License");
8    * you may not use this file except in compliance with the License.
9    * You may obtain a copy of the License at
10   *
11   *      http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
18   * #L%
19   */
20  package io.wcm.maven.plugins.i18n;
21  
22  import java.io.IOException;
23  import java.io.StringReader;
24  import java.io.StringWriter;
25  import java.util.Map;
26  
27  import jakarta.json.Json;
28  import jakarta.json.JsonObject;
29  import jakarta.json.JsonReader;
30  import jakarta.json.JsonReaderFactory;
31  import jakarta.json.JsonWriter;
32  import jakarta.json.JsonWriterFactory;
33  import jakarta.json.stream.JsonGenerator;
34  import jakarta.json.stream.JsonParsingException;
35  
36  /**
37   * Helper methods for JSON handling.
38   */
39  public final class JsonUtil {
40  
41    private static final JsonWriterFactory JSON_WRITER_FACTORY = Json.createWriterFactory(Map.of(
42        JsonGenerator.PRETTY_PRINTING, true));
43  
44    private static final JsonReaderFactory JSON_READER_FACTORY = Json.createReaderFactory(Map.of(
45        "org.apache.johnzon.supports-comments", true));
46  
47    private JsonUtil() {
48      // static methods only
49    }
50  
51    /**
52     * Serialize JSON object to String.
53     * @param jsonObject JSON object
54     * @return String
55     */
56    public static String toString(JsonObject jsonObject) {
57      StringWriter writer = new StringWriter();
58      try (JsonWriter jsonWriter = JSON_WRITER_FACTORY.createWriter(writer)) {
59        jsonWriter.write(jsonObject);
60        return writer.toString();
61      }
62    }
63  
64    /**
65     * Parse JSON string to JSON object.
66     * @param jsonString JSON string
67     * @return JSON object
68     * @throws IOException if JSON parsing fails
69     */
70    public static JsonObject fromString(String jsonString) throws IOException {
71      StringReader reader = new StringReader(jsonString);
72      try (JsonReader jsonReader = JSON_READER_FACTORY.createReader(reader)) {
73        return jsonReader.readObject();
74      }
75      catch (JsonParsingException ex) {
76        throw new IOException(ex.getMessage(), ex);
77      }
78    }
79  
80  }