以下是使用不同语言实现JSON响应API的解决方法,包含了代码示例:
from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/api/data', methods=['GET'])
def get_data():
data = {
'id': 1,
'name': 'John Doe',
'age': 25
}
return jsonify(data)
if __name__ == '__main__':
app.run()
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@SpringBootApplication
public class ApiApplication {
public static void main(String[] args) {
SpringApplication.run(ApiApplication.class, args);
}
@GetMapping("/api/data")
public Data getData() {
Data data = new Data(1, "John Doe", 25);
return data;
}
public static class Data {
private int id;
private String name;
private int age;
public Data(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
// getters and setters
}
}
const express = require('express');
const app = express();
app.get('/api/data', (req, res) => {
const data = {
id: 1,
name: 'John Doe',
age: 25
};
res.json(data);
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
class ApiController < ApplicationController
def data
data = {
id: 1,
name: 'John Doe',
age: 25
}
render json: data
end
end
以上示例展示了在不同语言中实现JSON响应API的一些常见方法。请注意,代码示例可能需要根据具体的应用程序和框架进行调整。
上一篇:不同语言的城市名称翻译问题