问题
I try to get parse an JSONArray from a PHP-Script in AndroidStudio. I get this JSON Response from my PHP script:
[{"0":"Firstname","meta_value":"Firstname"},{"0":"Lastname","meta_value":"Lastname"},{"valid":"1"},{"entered":"5"}]
Now I try to parse the JSONArray to get the value meta_value
so I want to get "Lastname" and "Firstname".
But there must be an error in my code because I get as response: Exception: No value for meta_value
public class SendPostRequest extends AsyncTask<String, Void, String> {
String data ="";
String dataParsed = "";
String singleParsed ="";
protected void onPreExecute(){}
protected String doInBackground(String... arg0) {
try {
URL url = new URL("https://sample.com/code2.php"); // here is your URL path
JSONObject postDataParams = new JSONObject();
postDataParams.put("sdata", scannedData);
Log.e("params",postDataParams.toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode=conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader in=new BufferedReader(new
InputStreamReader(
conn.getInputStream()));
StringBuffer sb = new StringBuffer("");
String line="";
while((line = in.readLine()) != null) {
data = data + line;
sb.append(line);
break;
}
in.close();
JSONArray reader2 = new JSONArray(data);
for(int i =0 ;i <reader2.length(); i++){
JSONObject JO = (JSONObject) reader2.get(i);
singleParsed = "Name:" + JO.get("meta_value") + "\n";
dataParsed = dataParsed + singleParsed +"\n" ;
}
return dataParsed;
}
else {
return new String("false : "+responseCode);
}
}
catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
@Override
protected void onPostExecute(String result) {
Toast.makeText(getApplicationContext(), result,
Toast.LENGTH_LONG).show();
}
}
Please dont mark my Answer as duplicate because I searched for 2 weeks and but havent found an Answer! Thank you:)
回答1:
I would suggest you to use GSON for serializing and deserializing your JSON responses. It makes it quite easy to handle then. GSON.
Sample:
new Gson().fromJson("YourJsonHere",JsonElement.class);
Cheers Tarik
来源:https://stackoverflow.com/questions/58342925/parse-jsonarray-in-android-studio