我正在尝试使用volley将JsonArray从php提取到android。但我收到以下错误。
org.json.JSONException: Value <!-- of type java.lang.String cannot be converted to JSONObject
以下是我从php获得的JsonArray响应。
{
"result": [
{
"subject_name": "Entrepreneurship",
"percentage": 1.1999999999999999555910790149937383830547332763671875
},
{
"subject_name": "Advanced Computing Platform",
"percentage": 1.1399999999999999023003738329862244427204132080078125
},
{
"subject_name": "Enterprise Application Platforms",
"percentage": 0
},
{
"subject_name": "Major Project",
"percentage": 0.340000000000000024424906541753443889319896697998046875
}
]
}
以下是我用来从db获取JsonArray的PHP代码。
$get = mysqli_query($conn, "SELECT * FROM subject_dtls WHERE course_sem='$student_course'");
while($row = mysqli_fetch_array($get))
{
$sub_id = $row['subject_id'];
$subject_name = $row['subject_name'];
$total_hours = $row['total_hours'];
$get12 = mysqli_query($conn, "SELECT sum(duration) as du_sum FROM attendance_count WHERE subject_id='$sub_id' AND roll_numbers = '$official_id'");
while($row12 = mysqli_fetch_array($get12))
{
$duration = $row12['du_sum'];
if ($duration=='')
{
$duration = 0;
}
$percentage = 0;
$percentage = ($duration * $total_hours)/100;
$temp = array();
$temp["subject_name"] = $subject_name;
$temp["percentage"] = $percentage;
$value["result"][] = $temp;
}
}
echo json_encode($value);
以下是我用来获取Json响应的Java代码。
public void onResponse(JSONObject response) {
try {
JSONArray result = response.getJSONArray("result");
for (int i = 0; i < result.length(); i++) {
JSONObject jsonObject = result.getJSONObject(i);
String subject_name = jsonObject.getString("subject_name");
String percentage = jsonObject.getString("percentage");
// Each time create a new instance and then save the value.
CheckAttendanceAdapter caa = new CheckAttendanceAdapter();
caa.setSubject_name(subject_name);
caa.setPercentage(percentage);
arrayList.add(caa);
}
data = new String[arrayList.size()][10];
for (int j = 0; j < arrayList.size(); j++) {
CheckAttendanceAdapter c = arrayList.get(j);
data[j][0] = c.getSubject_name();
data[j][1] = c.getPercentage();
tableView.setDataAdapter(new SimpleTableDataAdapter(getActivity(), data));
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
以下是错误的屏幕截图。
请告诉我,我做错了什么。
答案 0 :(得分:0)
我不知道您是否需要手动解析JSON响应,或者只是您不知道还有其他方式来使用REST服务。
我建议您使用Retrofit库来构建REST客户端。它易于编写且易于维护。要使用Retrofit使用REST服务,您需要编写服务接口和相关模型:
Fruit
和REST客户端:
public class Result {
public String subject_name;
public double percentage;
}
public class YourResponse {
List<Result> result;
}
调用您服务的代码:
public interface YourService {
@GET("result")
Call<YourResponse> getResult();
}
有关改造的更多信息是here。