MST

星途 面试题库

面试题:Kotlin 与 Node.js 交互时的数据序列化与反序列化

在 Kotlin 与 Node.js 进行后端开发交互过程中,假设 Kotlin 端有一个自定义的数据类 `User`,包含 `name`(字符串类型)和 `age`(整型)两个属性。请描述如何在 Kotlin 端将 `User` 实例序列化为 JSON 格式数据发送给 Node.js 端,并且在 Node.js 端如何反序列化该 JSON 数据为相应的对象结构。同时说明在 Kotlin 中常用的序列化库以及在 Node.js 中常用的反序列化方式。
22.7万 热度难度
编程语言Kotlin

知识考点

AI 面试

面试题答案

一键面试

Kotlin 端

  1. 常用序列化库
    • Gson:Google 开发的 JSON 处理库。首先在 build.gradle.kts 中添加依赖:
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 端
}
  1. 发送数据:可以使用网络请求库如 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 端

  1. 常用反序列化方式
    • 内置 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}`);
});