Reputation: 41
Hello i´m new in Android and searching the whole morning for a solution. I have only found posts which could not help me. The interessting post from JSON to 2D array dont worked in my project. I tried on different ways to implement this method into my code. I just want to convert my JSON response into a 2D String Array like this format:
Array[0][0] = Artikelnummer;
Array[0][1] = Preis;
Array[0][2] = Von;
Array[0][3] = Bis;
Array[0][4] = art_link;
Array[1][0] = Artikelnummer;
Array[1][1] = Preis;
Array[1][2] = Von;
Array[1][3] = Bis;
Array[0][4] = art_link;
.....
...
..
The JSON response looks like:
[{
"Artikelnummer": 01578675,
"Preis": 3.27,
"Von": "2017-10-16 08:00:00",
"Bis": "2017-10-20 13:00:00",
"art_link": "http://link/.jpg"
},
{
"Artikelnummer": 99999999,
"Preis": 9.99,
"Von": "2017-10-16 08:00:00",
"Bis": "2017-10-20 13:00:00",
"art_link": "http://link/.jpg"
},
{
"Artikelnummer": 55555555,
"Preis": 5.55,
"Von": "2017-10-16 08:00:00",
"Bis": "2017-10-20 13:00:00",
"art_link": "http://link/.jpg"
},
{
"Artikelnummer": 88888888,
"Preis": 8.88,
"Von": "2017-10-16 08:00:00",
"Bis": "2017-10-20 13:00:00",
"art_link": "http://link/.jpg"
}]
I get my response on this way:
URL url = new URL("https://myjson.com");
HttpURLConnection httpURLConnection = (HttpURLConnection)
url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new
InputStreamReader(inputStream));
String line = "";
while(line != null){
line = bufferedReader.readLine();
data = data + line;
ArrayList<String> listdata = new ArrayList<>();
JSONArray jArray = new JSONArray(data);
for(int i =0 ;i <jArray.length(); i++){
listdata.add(jArray.getString(i));
JSONObject jObject = (JSONObject) jArray.get(i);
}
But how I can convert my jArray response into a String[][]
Something like this, but this didn´t work for my project
String[][] matrix = new String[jArray.length][5];
Upvotes: 1
Views: 1742
Reputation: 521419
Parse your JSON string into a JSONArray
, then iterate over it and populate a given row in a 2D array of strings.
JSONArray json = new JSONArray(data);
String[][] array = new String[json.length()][5];
for (int i=0; i < json.length(); i++) {
JSONObject obj = json.getJSONObject(i);
array[i][0] = String.valueOf(obj.getInt("Artikelnummer"));
array[i][1] = String.valueOf(obj.getDouble("Preis"));
array[i][2] = obj.getString("Von");
array[i][3] = obj.getString("Bis");
array[i][4] = obj.getString("art_link");
}
Upvotes: 2