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?
CodePudding user response:
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);
});
CodePudding user response:
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.