你好,我是Android新手,整个上午都在寻找解决方案。 我只找到了无法帮助我的帖子。有趣的帖子from JSON to 2D array在我的项目中没有用。我试着用不同的方法将这个方法实现到我的代码中。 我只想将我的JSON响应转换为2D字符串数组,如下所示:
数组[0] [0] = Artikelnummer;
数组[0] [1] = Preis;
数组[0] [2] =冯;
数组[0] [3] = Bis;
数组[0] [4] = art_link;
数组[1] [0] = Artikelnummer;
数组[1] [1] = Preis;
数组[1] [2] = Von;
数组[1] [3] = Bis;
数组[0] [4] = art_link;
.....
...
...
JSON响应如下:
[{
"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"
}]
我以这种方式得到了回复:
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);
}
但是如何将我的jArray响应转换为String [] []
这样的事情,但这对我的项目不起作用
String[][] matrix = new String[jArray.length][5];
答案 0 :(得分:2)
将您的JSON字符串解析为JSONArray
,然后对其进行迭代并在2D字符串数组中填充给定行。
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");
}