如何在Kotlin中解析JSON数组 [英] How do I parse through JSON Arrays in Kotlin
问题描述
所以我正在开发一个Android应用程序,我需要从mysql数据库中获取用户列表,并将其数据放入kotlin应用程序中的User类中.
so I am working on an Android app and I need to get a list of users from my mysql database and put their data into a User class in my kotlin app.
php api正常工作,我在JSON中收到Postman的以下响应:
The php api is working correctly and I get this response with Postman in JSON:
{
"id": "5f69bbc1b264c6.07041576",
"username": "Test F",
"email": "test@gmail.com",
"profileimagepath": "../uploads/profileimages/5f69bbc1b264c6.07041576.jpg"
}{
"id": "5f69c5708632f7.37478122",
"username": "Test H",
"email": "test@gmail.com",
"profileimagepath": "../uploads/profileimages/5f69c5708632f7.37478122.jpg"
}
kotlin中的用户类如下:
The user class in kotlin looks like this:
class UserItem(val id: String, val username: String, val email: String){
constructor(): this("","","")
}
https请求的响应侦听器如下所示:
And the response listener for the https request looks like this:
val request = JsonObjectRequest(Request.Method.POST,url,jsonObject,
Response.Listener { response ->
// Process the json
try {
Log.d("loadTag", response.toString())
if(response.getString("error") == "false"){
Toast.makeText(applicationContext, "Loading completed!", Toast.LENGTH_SHORT).show()
}
else if(response.getString("error") == "true" && response.getString("message") == "Invalid code"){
Toast.makeText(applicationContext, "Invalid code.", Toast.LENGTH_LONG).show()
}
else if(response.getString("error") == "true" && response.getString("message") == "Required Parameters are missing"){
Toast.makeText(applicationContext, "Invalid user details or fields are empty.", Toast.LENGTH_LONG).show()
}
else if(response.getString("error") == "true"){
Toast.makeText(applicationContext, "Error. Something went wrong. Please try again.", Toast.LENGTH_LONG).show()
}
}catch (e:Exception){
Toast.makeText(applicationContext, "Something went wrong. Please try again.", Toast.LENGTH_LONG).show()
}
}, Response.ErrorListener{
// Error in request
Toast.makeText(applicationContext, "Error in http request. Please contact the developer.", Toast.LENGTH_LONG).show()
})
我已经尝试了很多东西,在这里和其他帖子上都读到了,但是我总是只得到一行(用户"Test F")
I've tried so many things that I've read here and on other posts but I always only get one row (user "Test F")
使用杰克逊进行更新
我仍然只有一个使用此代码的用户
I still get only one of the users using this code
when {
response.getString("error") == "true" && response.getString("message") == "Required Parameters are missing" -> {
Toast.makeText(applicationContext, "Invalid user details or fields are empty.", Toast.LENGTH_LONG).show()
}
response.getString("error") == "true" -> {
Toast.makeText(applicationContext, "Something went wrong. Please try again.", Toast.LENGTH_LONG).show()
}
else -> {
val mapper = ObjectMapper()
val users: UserItem = mapper.readValue(response.toString(), UserItem::class.java)
System.out.println(users)
Toast.makeText(applicationContext, "Loading completed.", Toast.LENGTH_LONG).show()
}
}
我通过以下代码从api获得json响应:
I get my json response from the api through this code:
$stmt2 = $this->con->prepare("SELECT id,username,email FROM accounts WHERE id=?");
$stmt2->bind_param("s", $friendsArray2);
if($stmt2->execute()){
$result2 = $stmt2->get_result();
$num_of_rows2 = $result2->num_rows;
while($row2 = mysqli_fetch_assoc($result2)){
$index++;
$index2++;
echo json_encode($row2);
}
}
还有更多代码,但这是给我响应的部分,因为我希望在sql语句中找到行
There is more code but this is the part that gives me the response as I want the rows found in the sql statement
推荐答案
已经有一段时间没有使用PHP了,但是如果我理解正确的话,您想将对象数组作为Json服务.
Haven't used PHP for a while, but if I understand correctly you want to serve the array of Objects as Json.
$stmt2 = $this->con->prepare("SELECT id,username,email FROM accounts WHERE id=?");
$stmt2->bind_param("s", $friendsArray2);
if($stmt2->execute()){
$result2 = $stmt2->get_result();
$num_of_rows2 = $result2->num_rows;
$result_array = array();
while($row2 = mysqli_fetch_assoc($result2)){
$index++;
$index2++;
result_array[] = $row2;
}
echo json_encode(result_array); // echo or do whatever with the encoded json
}
这会将所有行数据推送到数组,最后将数据编码为正确的Json表示形式,然后回显(输出)到控制台/服务器.
This will push all the row data to the array, and finally will encode the data as a proper Json representation, then will echo (output) to the console/server.
然后,您可以使用 kotlinx.serialization 轻松地将JsonArray解码为列表:>
And then you can easily decode the JsonArray into list using kotlinx.serialization:
@Serializable
data class Project(val id: String, val username: String, val email: String)
// response <= the Json response body, you get from HTTP response
val list: List<UserItem> = JSON.parse(UserItem.serializer().list, response)
这篇关于如何在Kotlin中解析JSON数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!