gpt4 book ai didi

java - 使用 JSON 从字符串中解析数组?

转载 作者:行者123 更新时间:2023-11-30 05:07:05 26 4
gpt4 key购买 nike

我正在向返回 JSON 编码数组的 php 文件发送一个 GET HTTP 请求。返回的 Array 是一个 2x2 Array。我如何解析 HTTP 请求的输出并在 Java 中制作一个 2x2 Array 例如String[][]ArrayList

请求.php:

<?php
$return_array = [["c1_r1", "c1_r2", "c1_r3"], ["c2_r1", "c2_r2", "c2_r3"], ["c3_r1", "c3_r2", "c3_r3"]];
echo json_encode($return_array);
?>

MainActivity.java:

package com.example.test;

import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.*;
import android.util.*;

import java.io.*;
import java.net.*;
import java.util.*;

public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

StrictMode.ThreadPolicy mypolicy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(mypolicy);

try {
URL url = new URL("http://192.168.1.XXX/request.php");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuilder sb = new StringBuilder();
sb.append(reader.readLine());

// HOW TO CONVERT/PARSE THE `sb` String INTO `String[][]`, JUST LIKE THE 2x2 Array STORED IN THE `request.php`

Log.e("console", sb.toString());

reader.close();
con.disconnect();
} catch (Exception e) {
Log.e("console", "FAIL " + e);
}
}
}

最佳答案

这是我用来转换您提供的编码 JSON 的代码(经过测试)。

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;

public class MainActivity extends Activity {

private static JSONArray itemRows = null;
private static String input =
"[[\"c1_r1\", \"c1_r2\", \"c1_r3\"]," +
"[\"c2_r1\", \"c2_r2\", \"c2_r3\"]," +
"[\"c3_r1\", \"c3_r2\", \"c3_r3\"]]";
private static String[][] output = new String[3][3];

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// build the Array[][] from the encoded JSON
try {
itemRows = new JSONArray(input);
Log.v("TestJSON","items.length=" + itemRows.length());
Log.v("TestJSON","input=" + input);
for(int i=0; i<itemRows.length(); i++){
JSONArray tmpR = itemRows.getJSONArray(i);
Log.v("TestJSON","i=" + i + " value=" + tmpR.toString());
// Loop over each row
Log.v("TestJSON","tmpR.length=" + tmpR.length());
for(int j=0; j<tmpR.length(); j++){
String tmpC = tmpR.get(j).toString();
output[i][j] = tmpC;
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}

关于java - 使用 JSON 从字符串中解析数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54384607/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com