Parse JSON in java (custom) - java

I have a JSON array in the following format:
[["1234","OS","01/31/2023","02/01/2023","First Day"],["1245","OS","01/23/2023","01/24/2023","Last Day"],["3411","OS","09/21/2022","09/21/2022","Second Day"]]
In Java, I would like to parse this array and store data in the following format:
String[] firstElements = ["1234" , "1245", "3411"];
String[] secondElements = ["OS", "OS", "OS"];
String[] thirdElements = ["01/31/2023", "01/23/2023", "09/21/2022"];
String[] fourthElements = ["02/01/2023", "01/24/2023", "09/21/2022"];
String[] fifthElements = ["First Day", "Last Day", "Second Day"];
Is this possible? How can I achieve this?

String jsonArray = "[[\"1234\",\"OS\",\"01/31/2023\",\"02/01/2023\",\"First Day\"],[\"1245\",\"OS\",\"01/23/2023\",\"01/24/2023\",\"Last Day\"],[\"3411\",\"OS\",\"09/21/2022\",\"09/21/2022\",\"Second Day\"]]";
JsonArray array = Json.createReader(new StringReader(jsonArray)).readArray();
List<String> firstElements = new ArrayList<>();
List<String> secondElements = new ArrayList<>();
List<String> thirdElements = new ArrayList<>();
List<String> fourthElements = new ArrayList<>();
List<String> fifthElements = new ArrayList<>();
array.forEach( value -> {
JsonArray innerArray = value.asJsonArray();
firstElements.add(innerArray.getString(0));
secondElements.add(innerArray.getString(1));
thirdElements.add(innerArray.getString(2));
fourthElements.add(innerArray.getString(3));
fifthElements.add(innerArray.getString(4));
)};
If you want something more generic you can use a List<List<String>>
String jsonArray = "[[\"1234\",\"OS\",\"01/31/2023\",\"02/01/2023\",\"First Day\"],[\"1245\",\"OS\",\"01/23/2023\",\"01/24/2023\",\"Last Day\"],[\"3411\",\"OS\",\"09/21/2022\",\"09/21/2022\",\"Second Day\"]]";
JsonArray array = Json.createReader(new StringReader(jsonArray)).readArray();
List<List<String>> elements = new ArrayList<>();
array.forEach( value -> {
JsonArray innerArray = value.asJsonArray();
List<String> subElements = new ArrayList<>();
for (int i = 0; i < innerArray.size(); i++) {
subElements.add(innerArray.getString(i));
}
elements.add(subElements);
});

There are a few solutions to parsing JSON from Java, like GSON, though if the data format you are working with is simple enough and you don't have to parse all kinds of JSON, you might as well parse it by yourself.

Related

How to read CSV in Hazelcast jet in List<Map> or JsonArray format?

As I am new to hazelcast am I trying few thing but not getting result as I accepted, please help me out.
Here is my below code which I am trying but not getting success.
BatchSource<List> companyListBatchSource = FileSources.files("directory")
.glob("name.csv")
.format(FileFormat.csv(List.class))
.build();
pipeline.readFrom(companyListBatchSource)
.writeTo(Sinks.list("mapName"));
Let me know how can we read it in List<Map<String, Object>> or JsonArray?
You can pass a list of field-names if you don't want to convert the values to a dedicated record, in that case you'll get a String[] as a record.
List<String> fieldNames = new ArrayList<>();
fieldNames.add("foo");
fieldNames.add("bar");
BatchSource<String[]> source = FileSources.files("directory")
.glob("file.csv")
.format(FileFormat.csv(fieldNames))
.build();
And if you don't know the fields beforehand, you can pass null as the list of field-names.
You can also create a custom file source like below
BatchSource<Map<String, String>> source = Sources.filesBuilder("directory")
.glob("file.csv")
.build(path -> {
Stream<String> lines = Files.lines(path);
String[][] headers = new String[1][];
return lines.filter(line -> {
if (headers[0] == null) {
headers[0] = line.split(",");
return false;
}
return true;
}).map(line -> {
String[] values = line.split(",");
Map<String, String> map = new HashMap<>();
for (int i = 0; i < headers[0].length; i++) {
String header = headers[0][i];
String value = values[i];
map.put(header, value);
}
return map;
});
});

Connect two HashMap Values

I've got this JSON string:
String json = "{\"countries\":{\"2\":\"China\",\"3\":\"Russia \",\"4\":\"USA\"},\"capitals\":{\"2\":Beijing,\"4\":null,\"3\":Moscow}}";
I converted string to HashMap, using this:
HashMap<String,Object> map = new Gson().fromJson(json, new TypeToken<HashMap<String, Object>>(){}.getType());
System.out.println(map.get("countries")+"#####"+map.get("capitals"));
And now my output is:
{2=China, 3=Russia , 4=USA}#####{2=Beijing, 4=null, 3=Moscow}
I would like to connect this values by numbers. I want to create two ArrayList like this:
A)- [China,Russia,USA]
B)- [Beijing,Moscow,null]
How can i do it?
First, you need to cast map.get("label") to LinkedTreeMap<Integer, String>, then create new ArrayList with it's values
String json = "{\"countries\":{\"2\":\"China\",\"3\":\"Russia \",\"4\":\"USA\"},\"capitals\":{\"2\":Beijing,\"4\":null,\"3\":Moscow}}";
HashMap<String,TreeMap<Integer, String>> map = new Gson().fromJson(json, new TypeToken<HashMap<String, TreeMap<Integer, String>>>(){}.getType());
ArrayList<String> countries = new ArrayList<>(map.get("countries").values());
System.out.println(countries);
ArrayList<String> capitals = new ArrayList<>(map.get("capitals").values());
System.out.println(capitals);
You can iterate over the country keyset to fill the capital array:
List<String> countries = new ArrayList<>(countriesMap.values());
List<String> capitals = new ArrayList<>();
for (String countryKey : countriesMap.keySet()) {
capitals.add(capitalsMap.get(countryKey));
}

Can I use a for loop to build a JsonObject with Json.createObjectBuilder?

I'm trying to build a new JsonObject with some values from different existing JsonObjects. I want to store the names of the values in for example a separate file, string...
JsonObject object1 = ...;
JsonObject object2 = ...;
String [] names1 = { ... };
String [] names2 = { ... };
JsonObject newObject = Json.createObjectBuilder()
.add(names1[0], object1.getString(names1[0]))
.add(names1[1], object1.getString(names1[1]))
...
.add(names2[0], object2.getString(names2[0]))
.add(names2[1], object2.getString(names2[1]))
...
.build();
Can I instead add the names and values to the newObject using two foreach loops? This would allow me to change the names and fields that have to be added.
Yes, you can do that, just keep the JsonObjectBuilder object:
JsonObject object1 = ...;
JsonObject object2 = ...;
String [] names1 = { ... };
String [] names2 = { ... };
JsonObjectBuilder builder = Json.createObjectBuilder();
for(String name: names1)
builder.add(name, object1.getString(name));
for(String name: names2)
builder.add(name, object2.getString(name));
JsonObject newObject = builder.build();
Yes. You can iterate names1 and names2 variable's with two for loops and build the same logic you did here.

How to convert Optional<JsonObject> to List<String>

I have some api parameters which I have received from a json file in test method. Now I need to convert this object to a list, because it contains arrays that I would like to handle individually.
#SuppressWarnings("unchecked")
static Optional getQueryParametersTEST(JsonObject inputJsonObject) {
JsonObject operators = inputJsonObject.getJsonObject("operators");
JsonObject tez = operators.getJsonObject("tez");
JsonArray parameters = tez.getJsonArray("parameters");
Optional<JsonObject> queryParameters = parameters.stream().
filter(JsonObject.class::isInstance).
map(JsonObject.class::cast).
filter(jsonObject -> jsonObject.getJsonObject("queryParameters") != null).
map(item -> item.getJsonObject("queryParameters")).
findFirst();
return queryParameters;
}
after i received queryParameters it comes in this format
Optional[{"priceMin":["0"],"priceMax":["150000"],"currency":["5561"],"hotelClassId":[""],"accommodationId":["158525","9002884","1"],"rAndBId":["15350","2424","2474","2749","5737","5738"]}
What can i do to get a list of Strings
I tried to perform a
return queryParameters.ifPresent(newList::add)
.flatMap(Optional::stream)
.collect(Collectors.toList());
Tried using this but Jsonobject requires a source of string but i have queryParameters of type Optional queryParameters
JSONObject obj = new JSONObject(my source should be the query param )
List<String> list = new ArrayList<String>();
JSONArray array = obj.getJSONArray("interests");
for(int i = 0 ; i < array.length() ; i++){
list.add(array.getJSONObject(i).getString("interestKey"));
}
JSONObject obj = new JSONObject("{interests : [{interestKey:Dogs}, {interestKey:Cats}]}");
List<String> list = new ArrayList<String>();
JSONArray array = obj.getJSONArray("interests");
for(int i = 0 ; i < array.length() ; i++){
list.add(array.getJSONObject(i).getString("interestKey"));
}

Insert String array in JSON plain-text

I've created some JSON strings in Java but I don't know how to insert string array.
For example, I've want to add string the format is:
String aux1 = "{ \"key\" : \"value\"};
But if i want to add as value: new String[] {"string1", "string2"};
How I can represent a string array in text-plain format??
Thanks
Use the JSONObject class :
JSONObject object = new JsonObject();
object.put("key1", "value1");
object.put("key2", "value2");
String jsonString = object.toString(); //This will create the corresponding JSON-formatted string
You can use something like this:
String[] strArray = new String[] {"string1", "string2"};
JSONObject jo = new JSONObject();
jo.put("key", Arrays.asList(strArray));
Output would be:
{"key":["string1","string2"]}
String[] strArray = new String[] {"string1", "string2"};
String str1 = Arrays.toString(strArray);
JSONObject jobj = new JSONObject();
jobj.put("yourstringKey",str1);
you can do above way only if your strArray size is more(supose greater than 10.) But if your array is small.then use following way.
JSONObject jobj1=new JSONObject();
jobj1.put("key1","value1");
jobj1.put("key2","value2");
JSONObject jobj=new JSONObject();
jobj.put("mystring",jobj1.toStirng());

Categories