面试题答案
一键面试Kotlin 端
- 常用序列化库:
- Gson:Google 开发的 JSON 处理库。首先在
build.gradle.kts
中添加依赖:
- Gson:Google 开发的 JSON 处理库。首先在
implementation("com.google.code.gson:gson:2.8.6")
然后在代码中使用:
import com.google.gson.Gson
data class User(val name: String, val age: Int)
fun main() {
val user = User("John", 30)
val gson = Gson()
val json = gson.toJson(user)
println(json)
// 这里可以将 json 数据发送给 Node.js 端
}
- Moshi:Square 开发的 JSON 库,性能较好。在
build.gradle.kts
中添加依赖:
implementation("com.squareup.moshi:moshi:1.12.0")
代码使用如下:
import com.squareup.moshi.Moshi
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
data class User(val name: String, val age: Int)
fun main() {
val moshi = Moshi.Builder()
.add(KotlinJsonAdapterFactory())
.build()
val adapter = moshi.adapter(User::class.java)
val user = User("John", 30)
val json = adapter.toJson(user)
println(json)
// 这里可以将 json 数据发送给 Node.js 端
}
- 发送数据:可以使用网络请求库如
OkHttp
将序列化后的 JSON 数据发送到 Node.js 服务端。例如:
import okhttp3.MediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import java.io.IOException
data class User(val name: String, val age: Int)
fun main() {
val user = User("John", 30)
val gson = Gson()
val json = gson.toJson(user)
val client = OkHttpClient()
val mediaType = MediaType.parse("application/json")
val requestBody = RequestBody.create(mediaType, json)
val request = Request.Builder()
.url("http://your - nodejs - server - url")
.post(requestBody)
.build()
client.newCall(request).enqueue(object : okhttp3.Callback {
override fun onFailure(call: okhttp3.Call, e: IOException) {
e.printStackTrace()
}
override fun onResponse(call: okhttp3.Call, response: okhttp3.Response) {
response.use {
if (!response.isSuccessful) throw IOException("Unexpected code $response")
println(response.body()!!.string())
}
}
})
}
Node.js 端
- 常用反序列化方式:
- 内置
JSON.parse
:Node.js 内置的方法。假设接收到的 JSON 数据在req.body
中(使用 Express 框架示例):
- 内置
const express = require('express');
const app = express();
app.use(express.json());
app.post('/', (req, res) => {
const { name, age } = req.body;
const user = { name, age };
console.log(user);
res.send('User received successfully');
});
const port = 3000;
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
- 使用第三方库如
joi
:用于数据验证和解析。首先安装joi
:
npm install joi
代码如下:
const express = require('express');
const Joi = require('joi');
const app = express();
app.use(express.json());
const userSchema = Joi.object({
name: Joi.string().required(),
age: Joi.number().integer().min(0).required()
});
app.post('/', (req, res) => {
const { error, value } = userSchema.validate(req.body);
if (error) {
return res.status(400).send(error.details[0].message);
}
const user = value;
console.log(user);
res.send('User received successfully');
});
const port = 3000;
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});