Springboot xmlとjsonフォーマットの戻り
2807 ワード
Spring bootのrestインタフェース戻りフォーマットは、RequestMapping注記のproducesで指定できます.プロジェクトがjsonとxmlの戻りフォーマットを同時に満たす必要がある場合は、次のように手動で指定する必要があります.
その中のアプリケーション/xmlとアプリケーション/jsonはxmlまたはjsonを使用して結果を返すことを表しますが、どのフォーマットを返すべきかは何で判断しますか?これは主に呼び出し者によって指定されます.
义齿jsonの最後はjson形式で返されます.xmlの最後はxml形式で返されます.たとえば、次のようにします.http://localhost:8080/student.json?id=1導入パケット依存 2 xmlコンバータ を追加3エンティティクラスを新規作成します.ここではh 2メモリデータベースを使用して を実証します.4試験例 を記述する4テスト、ブラウザで入力http://localhost:8080/student.xml?id=1結果は、 です.
入力時http://localhost:8080/student.json?id=1の場合は次のようになります.
注意すべき点 kotlinのデフォルトのクラスと関数はfinalであるため、 を生成する必要があるためである.
@RequestMapping(value = "/student", produces = arrayOf("application/xml", "application/json"))
その中のアプリケーション/xmlとアプリケーション/jsonはxmlまたはjsonを使用して結果を返すことを表しますが、どのフォーマットを返すべきかは何で判断しますか?これは主に呼び出し者によって指定されます.
义齿jsonの最後はjson形式で返されます.xmlの最後はxml形式で返されます.たとえば、次のようにします.http://localhost:8080/student.json?id=1
com.fasterxml.jackson.dataformat
jackson-dataformat-xml
@Configuration
open class MyWebConfiguration : WebMvcConfigurerAdapter() {
@Bean
open fun jacksonXmlConverter() = MappingJackson2XmlHttpMessageConverter()
override fun configureMessageConverters(converters: List>) {
(converters as MutableList).add(jacksonXmlConverter())
}
}
@Entity
data class Student (val name: String, val age: Int, @Id @GeneratedValue(strategy=GenerationType.AUTO) var id: Int = 0) {
constructor() : this("", 0)
}
interface StudentRepository : JpaRepository
@SpringBootApplication
@RestController
open class ProfileDemoApplication : CommandLineRunner {
@Autowired
private lateinit var repo: StudentRepository
override fun run(vararg p0: String?) {
with(repo) {
//
save(Student("aaa", 10))
save(Student("bbb", 20))
save(Student("ccc", 30))
}
println("students are ${repo.findAll()}")
}
@RequestMapping("/hello")
fun sayHello() = "hello world"
@RequestMapping(value = "/student", produces = arrayOf("application/json", "application/xml"))
fun getStudentById(id: Int) : Student = repo.findOne(id)
companion object {
@JvmStatic
fun main(args: Array) {
SpringApplication.run(ProfileDemoApplication::class.java, *args)
}
}
}
aaa
10
1
入力時http://localhost:8080/student.json?id=1の場合は次のようになります.
{"name":"aaa","age":10,"id":1}
注意すべき点
@Configuration
および@Bean
によって修飾されたすべてのクラスまたは関数はopenとして定義される.主にspringが関連エージェントクラス