ca63b234a0e413aee48c4b664e78740202344b79
[aai/model-loader.git] / src / main / java / org / openecomp / modelloader / util / JsonXmlConverter.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * MODEL LOADER SERVICE
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
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  * ============LICENSE_END=========================================================
19  */
20
21 package org.openecomp.modelloader.util;
22
23 import org.json.JSONArray;
24 import org.json.JSONException;
25 import org.json.JSONObject;
26 import org.json.XML;
27
28 public class JsonXmlConverter {
29
30   /**
31    * Determines whether or not the supplied text string represents a valid
32    * JSON structure or not.
33    * 
34    * @param text - The text to be evaluated.
35    * 
36    * @return - true if the string represents a valid JSON object,
37    *           false, otherwise.
38    */
39   public static boolean isValidJson(String text) {
40     try {
41       new JSONObject(text);
42     } catch (JSONException ex) {
43       try {
44         new JSONArray(text);
45       } catch (JSONException ex1) {
46         return false;
47       }
48     }
49
50     return true;
51   }
52
53   /**
54    * Takes a text string representing a valid JSON structure and converts it to
55    * an equivalent XML string.
56    * 
57    * @param jsonText - The JSON string to convert to XML.
58    * 
59    * @return - An XML string representation of the supplied JSON string.
60    */
61   public static String convertJsonToXml(String jsonText) {
62     JSONObject jsonObj = new JSONObject(jsonText);
63     String xmlText = XML.toString(jsonObj);
64     return xmlText;
65   }
66
67   /**
68    * Takes a text string representing a valid XML structure and converts it to
69    * an equivalent JSON string.
70    * 
71    * @param xmlText - The XML string to convert to JSON.
72    * 
73    * @return - A JSON string representation of the supplied XML string.
74    */
75   public static String convertXmlToJson(String xmlText) {
76     JSONObject jsonObj = XML.toJSONObject(xmlText);
77     return jsonObj.toString();
78   }
79 }