1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
|
package com.mavlushechka.a1qa.utils;
import com.google.gson.Gson;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Map;
import java.util.TreeMap;
public class JsonParser {
private final static TreeMap<String, JSONObject> parsedJSON = new TreeMap<>();
public static String parseData(String filename, String key) {
return parse(filename, key, false);
}
public static String parseObject(String filename, String key) {
return parse(filename, key, true);
}
public static boolean isJson(String json) {
try {
new JSONObject(json);
} catch (JSONException jsonObjectException) {
try {
new JSONArray(json);
} catch (JSONException jsonArrayException) {
return false;
}
}
return true;
}
public static boolean isBodyEmpty(String json) {
return json.equals("{}");
}
public static <T> T convertToObject(String json, Class<T> classToConvert) {
return new Gson().fromJson(json, classToConvert);
}
public static <T> String convertToJson(T object) {
return new Gson().toJson(object);
}
public static <T> T[] convertArray(String json, Class<T> classToConvert) {
Gson gson = new Gson();
JSONArray jsonArray = new JSONArray(json);
ArrayList<T> objects = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
objects.add(gson.fromJson(jsonArray.getJSONObject(i).toString(), classToConvert));
}
return (T[]) objects.toArray();
}
private static String parse(String filename, String key, boolean isObject) {
Map.Entry<String, JSONObject> ceilingEntry = parsedJSON.ceilingEntry(filename);
if (ceilingEntry == null || !ceilingEntry.getKey().startsWith(filename)) {
parseFile(filename);
}
return parseData(filename, key, isObject);
}
private static void parseFile(String filename) {
parsedJSON.put(filename, new JSONObject(FileParser.parse("src/main/resources/" + filename + ".json")));
}
private static String parseData(String jsonName, String key, boolean isObject) {
JSONObject jsonObject = new JSONObject(parsedJSON.get(jsonName).toString());
String[] keys = key.split("\\.");
for (int i = 0; i < keys.length - 1; i++) {
if (keys[i].contains("[") && keys[i].contains("]")) {
String splitKey = keys[i].split("\\[")[0];
int index = Integer.parseInt(keys[i].split("\\[")[1].replaceAll("[\\[\\]]", ""));
jsonObject = jsonObject.getJSONArray(splitKey).getJSONObject(index);
} else {
jsonObject = jsonObject.getJSONObject(keys[i]);
}
}
if (isObject) {
return jsonObject.getJSONObject(keys[keys.length - 1]).toString();
}
return jsonObject.getString(keys[keys.length - 1]);
}
}
|