当前位置:网站首页>Utility gadget: kotlin code snippet
Utility gadget: kotlin code snippet
2022-07-27 05:24:00 【Master yuan】
List of articles
1. Convert any object to Map
inline fun <reified T : Any> T.asMap() : Map<String, Any?> {
val props = T::class.memberProperties.associateBy {
it.name }
return props.keys.associateWith {
props[it]?.get(this) }
}
2. practical ObjectMapper Convert objects
2.1 Object turn JsonString
data class Person(val name: String, var age: Int)
fun obj2JsonString(obj: Person){
val objectMapper = ObjectMapper().registerModule(JavaTimeModule()).disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS)
return objectMapper.writeValueAsString(person)
}
2.2 JsonString Transfer object
data class Person(val name: String = " ", var age: Int = 23)
fun getPersonFromJsonString(): Person {
val objectMapper = ObjectMapper().registerModule(JavaTimeModule()).disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS)
val jsonString = "{\"name\":\"tom\",\"age\":34}"
return objectMapper.readValue(jsonString, Person::class.java)
}
Be careful :
You can see , there data class Each field of is given a default value , If not , Will report a mistake :
Exception in thread "main" com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `com.example.Person` (no Creators, like default constructor, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
at [Source: (String)"{"name":"tom","age":34}"; line: 1, column: 2]
at com.fasterxml.jackson.databind.exc.InvalidDefinitionException.from(InvalidDefinitionException.java:67)
at com.fasterxml.jackson.databind.DeserializationContext.reportBadDefinition(DeserializationContext.java:1615)
at com.fasterxml.jackson.databind.DatabindContext.reportBadDefinition(DatabindContext.java:400)
at com.fasterxml.jackson.databind.DeserializationContext.handleMissingInstantiator(DeserializationContext.java:1077)
at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromObjectUsingNonDefault(BeanDeserializerBase.java:1332)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:331)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:164)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4524)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3466)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3434)
This is due to the lack of a parameterless constructor , and data class No parameterless constructor was generated , You need to add default values for each parameter , To generate a parameterless constructor .kotlin Official website There are 
For each data class Add default values for each attribute of , What an annoying thing ! Do you want everyone to write ? I don't want to .
Fortunately ,kotlin There are still official solutions :
Use no-arg Compiler plug-in , stay pom The following configuration is made in the file :
<plugin>
<artifactId>kotlin-maven-plugin</artifactId>
<groupId>org.jetbrains.kotlin</groupId>
<version>${kotlin.version}</version>
<configuration>
<compilerPlugins>
<!-- Or "jpa" for JPA support -->
<plugin>no-arg</plugin>
</compilerPlugins>
<pluginOptions>
<option>no-arg:annotation=com.my.Annotation</option>
<!-- Call instance initializers in the synthetic constructor -->
<!-- <option>no-arg:invokeInitializers=true</option> -->
</pluginOptions>
</configuration>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-noarg</artifactId>
<version>${kotlin.version}</version>
</dependency>
</dependencies>
</plugin>
2.3 JsonString Contained in the list
If json The string contains list, Then it should be written as :
data class Person(val name: String = " ", var age: Int = 23)
fun getPersonFromJsonString(): List<*> {
val objectMapper = ObjectMapper().registerModule(JavaTimeModule()).disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS)
val jsonString = "[{\"name\":\"tom\",\"age\":34},{\"name\":\"tom\",\"age\":34}]"
return objectMapper.readValue(jsonString, List::class.java)}
But the result is list in ,list Elements in are not recognized , But rather linkedHashMap The form is stored in list Medium . If I want to extract specific object types , It should be :
data class Person(val name: String = " ", var age: Int = 23)
fun getPersonFromJsonString(): List<*> {
val objectMapper = ObjectMapper().registerModule(JavaTimeModule()).disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS)
val jsonString = "[{\"name\":\"tom\",\"age\":34},{\"name\":\"tom\",\"age\":34}]"
var people: List<Person> = objectMapper.readValue(jsonString, objectMapper.typeFactory.constructCollectionType(List::class.java, Person::class.java))
return people
So you can get list Specific examples included in .
边栏推荐
- B1025 反转链表*******
- SSM framework integration
- 李宏毅机器学习组队学习打卡活动day04---深度学习介绍和反向传播机制
- Prime number screening (Ehrlich sieve method, interval sieve method, Euler sieve method)
- 秒杀系统设计
- 简化JDBC的MyBits框架
- Translation of robot and precise vehicle localization based on multi sensor fusion in diverse city scenes
- 整合SSM
- JVM Part 1: memory and garbage collection part 14 -- garbage collector
- Integrate SSM
猜你喜欢

整合SSM

torch中乘法整理,*&torch.mul()&torch.mv()&torch.mm()&torch.dot()&@&torch.mutmal()

ERROR! MySQL is not running, but PID file exists

Detailed description of binary search tree

35.滚动 scroll

稀疏数组→五子棋的存盘续盘等操作

redis集群

SQL数据库→约束→设计→多表查询→事务

Scientific Computing Library -- Matplotlib

The difference between strlen and sizeof
随机推荐
Translation of robot and precise vehicle localization based on multi sensor fusion in diverse city scenes
李宏毅机器学习组队学习打卡活动day06---卷积神经网络
What should test / development programmers over 35 do? Many objective factors
35.滚动 scroll
Alphabetic order problem
Detailed explanation of pointer constant and constant pointer
JVM上篇:内存与垃圾回收篇十一--执行引擎
File processing (IO)
Find the number of combinations (the strongest optimization)
SSM framework integration
Database connection pool & Druid usage
The interface can automatically generate E and other asynchronous access or restart,
秒杀系统设计
听过最自律的一句话: 那些我难以言表 不作声响
[optical flow] - data format analysis, flowwarp visualization
内部类与静态内部类区别及举例
B1028 人口普查
LeetCode刷题之322 Coin Change
Inspiration from "flying man" Jordan! Another "arena" opened by O'Neill
The provision of operation and maintenance manager is significantly affected, and, for example, it is like an eep command