fastJson心得

开启fastJson的autoType全局配置

fastjson autoType is not support,有@字符串报错,开启后消除

    @Bean
    fun fastJson(){
        ParserConfig.getGlobalInstance().isAutoTypeSupport = true
    }

转换成json

    fun parsePhone(phoneStr: String?): MutableList<Phone> {
        val jsonBody = JSONObject.toJSONString(phoneStr )
        val jsonObject = JSONObject.parseObject("{\"phone\": " + jsonBody + "}")
        val phoneList = mutableListOf<Phone>()
        val phones = jsonObject.getJSONArray("phone")
        val iteratorPhone = phones?.iterator()
        if (iteratorPhone != null) {
            while (iteratorPhone.hasNext()) {
                val next = iteratorPhone.next() as JSONObject
                val phone = Phone()
                phone.mobileNoAreaCode = next["phonearea"]?.toString()
                phone.mobileNo = next["phoneval"]?.toString()

                phoneList.add(phone)
            }
        }
        return phoneList
    }

便捷转换

快速获取shopCode 

                val shopResponse = RestTemplateUtils.getRestTemplate().exchange(
                    UriComponentsBuilder.fromHttpUrl(applicationProperties.globalCmsApiEndpoint + "/v1/api/shop_list")
                        .queryParam("get_type", "")
                        .queryParam("shopid", shop.shopId)
                        .queryParam("channel_id", "4")
                        .toUriString(),
                    HttpMethod.GET,
                    entity,
                    Object::class.java,
                )
                shop.shopCode = ((shopResponse.body as Map<*, *>)["result"] as List<Map<String, Object>>)
                    .find { it["shopid"].toString() == shop.shopId }?.get("shopcode").toString()
                shopList.add(shop)

不知道json数据的key和value,遍历并使用key获取value数据

        val shops = personnel.getJSONObject("shop")
        val jsonObj = JSON.parseObject(shops.toString())
        for ((key,value) in jsonObj){
            val shops = shops.getJSONArray(key)
            val iteratorShop = shops.iterator()
            while (iteratorShop.hasNext()) {
                val shopNext = iteratorShop.next() as JSONObject
                val shop = ShopDto()
                shop.shopId = shopNext["store_id"]?.toString()
                shop.locations.add(I18nString(LocaleUtils.SIMPLIFIED_CHINESE, shopNext["atitle"]?.toString() ?: ""))
                shop.locations.add(I18nString(LocaleUtils.TRADITIONAL_CHINESE, shopNext["tc_atitle"]?.toString() ?: ""))
                shop.locations.add(I18nString(LocaleUtils.ENGLISH, shopNext["en_atitle"]?.toString() ?: ""))
                shop.clinics.add(I18nString(LocaleUtils.SIMPLIFIED_CHINESE, shopNext["cn_name"].toString()))
                shop.clinics.add(I18nString(LocaleUtils.TRADITIONAL_CHINESE, shopNext["tc_name"].toString()))
                shop.clinics.add(I18nString(LocaleUtils.ENGLISH, shopNext["en_name"].toString()))
                shop.address.add(I18nString(LocaleUtils.SIMPLIFIED_CHINESE, parseAddress(shopNext["cn_address"]?.toString() ?: "")))
                shop.address.add(I18nString(LocaleUtils.TRADITIONAL_CHINESE, parseAddress(shopNext["tc_address"]?.toString() ?: "")))
                shop.address.add(I18nString(LocaleUtils.ENGLISH, parseAddress(shopNext["en_address"]?.toString() ?: "")))
                shop.mail = shopNext["mail"]?.toString()
                shop.phone = parsePhone(shopNext["phone"]?.toString())
                //TODO shopCode
                shopList.add(shop)
        }

----------------------------------------------------------------------
val regionJsonObject = next["region_list"]
            //补充,此处有数据时为object,没有数据时为空数组,需先判断
            if (regionJsonObject is JSONObject) {
                val jsonObj = JSON.parseObject(regionJsonObject.toString())
                for ((key, value) in jsonObj) {
                    val regionList = (regionJsonObject as JSONObject).getJSONArray(key)
                    val regionListIterator = regionList.iterator()
                    while (regionListIterator.hasNext()) {
                        val regionListNext = regionListIterator.next() as JSONObject
                        val shop = MongoDBShopsDto()
                        shop.shopId = regionListNext["shopid"]?.toString()
                        shop.shopCode = regionListNext["shopcode"]?.toString()
                        shop.regionId = regionListNext["x_id"]?.toString()
                        shop.locations.add(
                            I18nString(
                                LocaleUtils.SIMPLIFIED_CHINESE, regionListNext["atitle"]?.toString() ?: ""
                            )
                        )
                        shop.locations.add(
                            I18nString(
                                LocaleUtils.TRADITIONAL_CHINESE,
                                regionListNext["tc_atitle"]?.toString() ?: ""
                            )
                        )
                        shop.locations.add(
                            I18nString(
                                LocaleUtils.ENGLISH,
                                regionListNext["en_atitle"]?.toString() ?: ""
                            )
                        )
                        shop.clinics.add(
                            I18nString(
                                LocaleUtils.SIMPLIFIED_CHINESE,
                                regionListNext["cn_name"].toString()
                            )
                        )
                        shop.clinics.add(
                            I18nString(
                                LocaleUtils.TRADITIONAL_CHINESE,
                                regionListNext["tc_name"].toString()
                            )
                        )
                        shop.clinics.add(I18nString(LocaleUtils.ENGLISH, regionListNext["en_name"].toString()))
                        shop.address.add(
                            I18nString(
                                LocaleUtils.SIMPLIFIED_CHINESE,
                                parseAddress(regionListNext["cn_address"]?.toString() ?: "")
                            )
                        )
                        shop.address.add(
                            I18nString(
                                LocaleUtils.TRADITIONAL_CHINESE,
                                parseAddress(regionListNext["tc_address"]?.toString() ?: "")
                            )
                        )
                        shop.address.add(
                            I18nString(
                                LocaleUtils.ENGLISH,
                                parseAddress(regionListNext["en_address"]?.toString() ?: "")
                            )
                        )
                        shop.mail = regionListNext["mail"]?.toString()
                        shop.phone = parsePhone(regionListNext["phone"]?.toString())
                        shop.businessDays = parseBusinessDays(regionListNext["business_hours"]?.toString())
                        doctor.shops.add(shop)
                    }
                }
            }

处理json的星期数据

package com.umh.medicalbookingplatform.background.service

import com.umh.medicalbookingplatform.core.error.ErrorCode
import com.umh.medicalbookingplatform.core.exception.ApplicationException
import com.umh.medicalbookingplatform.core.properties.ApplicationProperties
import com.umh.medicalbookingplatform.core.utils.RestTemplateUtils
import com.alibaba.fastjson.JSONObject
import com.umh.medicalbookingplatform.core.model.i18n.I18nString
import com.umh.medicalbookingplatform.core.utils.LocaleUtils
import org.apache.commons.lang3.StringUtils
import org.keycloak.admin.client.Keycloak
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.data.domain.Pageable
import org.springframework.http.HttpEntity
import org.springframework.http.HttpHeaders
import org.springframework.http.HttpMethod
import org.springframework.http.ResponseEntity
import org.springframework.stereotype.Service
import org.springframework.web.util.UriComponentsBuilder
import java.lang.StringBuilder
import java.util.*
import com.alibaba.fastjson.JSON
import com.umh.medicalbookingplatform.core.model.doctor.*
import com.umh.medicalbookingplatform.core.utils.ApplicationJsonObjectMapper
import org.bson.Document
import org.springframework.data.mongodb.core.MongoTemplate
import org.springframework.data.mongodb.core.query.Criteria
import org.springframework.data.mongodb.core.query.Query


/**
 * @Description :
 * @Author xiaomh
 * @create 2021/9/8 14:27
 */

@Service
class ApiCmsInvokeService {

    private val dayArray = arrayOf("mon", "tue", "wed", "thu", "fri", "sat", "sun", "gong")


    private fun parseBusinessDays(businessHoursStr: String?): MutableList<BusinessHourDto> {
        val jsonObject = JSONObject.parseObject(businessHoursStr)
        return parseBusinessHours(jsonObject)

    }

    private fun parseBusinessHours(jsonObject: JSONObject?): MutableList<BusinessHourDto> {
        val businessHours = mutableListOf<BusinessHourDto>()
        for (i in dayArray.indices) {
            val hoursJson = jsonObject?.getJSONArray(dayArray[i])
            val iterator = hoursJson?.iterator() ?: mutableListOf<BusinessHourDto>().iterator()
            val hourDto = BusinessHourDto()
            while (iterator.hasNext()) {
                val next = iterator.next() as JSONObject
                hourDto.periods!!.add(
                    BusinessHourPeriodDto().apply {
                        this.startTime = next["starttime"]?.toString() ?: ""
                        this.endTime = next["endtime"]?.toString() ?: ""
                    }
                )
            }
            if (dayArray[i] == "gong") {
                hourDto.day = "holiday"
            } else {
                hourDto.day = dayArray[i]
            }
            businessHours.add(hourDto)
        }
        return businessHours
    }


}
        val obj = mapOf(
            "test" to "test",
            "inner_test" to mapOf(
                "value" to "123456"
            )
        )



        val requestBody = mapOf(
            "id" to umhId,
            "hkid" to value,
            "country" to when (idType) {
                PersonalIdType.HKID -> "1"
                PersonalIdType.CHINA_ID -> "2"
                PersonalIdType.MACAU_ID -> "5"
                PersonalIdType.OTHERS -> "6"
            }
        )
        val firstName = jsonObject.getJSONArray("firstName").toArray()
        val lastName = jsonObject.getJSONArray("lastName").toArray()        
        val objectMapper = ApplicationJsonObjectMapper()        
        dto.firstName = objectMapper.convertValue(firstName, Array<I18nString>::class.java).toMutableList()
        dto.lastName = objectMapper.convertValue(lastName, Array<I18nString>::class.java).toMutableList()

枚举应用

enum class PersonalIdType {
    HKID, CHINA_ID, MACAU_ID, OTHERS
}



    fun updateUmhMemberIdentificationDocumentNo(
        umhMemberId: String,
        umhId: String,
        idType: PersonalIdType,
        value: String
    ): Boolean {

        val requestBody = mapOf(
            "id" to umhId,
            "hkid" to value,
            "country" to when (idType) {
                PersonalIdType.HKID -> "1"
                PersonalIdType.CHINA_ID -> "2"
                PersonalIdType.MACAU_ID -> "5"
                PersonalIdType.OTHERS -> "6"
            }
        )

RestTemplate 和 WebClient

package com.umh.medicalbookingplatform.core.utils

import org.apache.http.impl.client.HttpClients
import org.springframework.http.HttpRequest
import org.springframework.http.MediaType
import org.springframework.http.client.ClientHttpRequestExecution
import org.springframework.http.client.ClientHttpRequestInterceptor
import org.springframework.http.client.ClientHttpResponse
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter
import org.springframework.retry.RetryContext
import org.springframework.retry.policy.SimpleRetryPolicy
import org.springframework.retry.support.RetryTemplate
import org.springframework.web.client.RestTemplate
import java.io.IOException


class RestTemplateUtils {

    companion object {
        fun getRestTemplate(timeOutTime :Int? = null, maxAttempt: Int? = null): RestTemplate {

            val httpClient = HttpClients.custom()
//                .setSSLSocketFactory(csf)
                //        .setProxy(proxy)
                .build()
            val requestFactory = HttpComponentsClientHttpRequestFactory()
            requestFactory.httpClient = httpClient
            if(timeOutTime != null) {
                requestFactory.setConnectTimeout(timeOutTime)
                requestFactory.setReadTimeout(timeOutTime)
            } else {
                requestFactory.setConnectTimeout(5 * 60 * 1000)
                requestFactory.setReadTimeout(5 * 60 * 1000)
            }

            val restTemplate = RestTemplate(requestFactory)

            if (maxAttempt != null) {
                restTemplate.interceptors.add(ClientHttpRequestInterceptor { request: HttpRequest?, body: ByteArray?, execution: ClientHttpRequestExecution ->
                    val retryTemplate = RetryTemplate()
                    retryTemplate.setRetryPolicy(SimpleRetryPolicy(maxAttempt))
                    try {
                        retryTemplate.execute<ClientHttpResponse, IOException> { context: RetryContext? ->
//                            println("start retrying .... ${context?.retryCount}")
                            execution.execute(request, body)
                        }
                    } catch (throwable: Throwable) {
                        throw RuntimeException(throwable)
                    }
                })
            }

            val supportedMediaTypes = ArrayList<MediaType>()
            supportedMediaTypes.add(MediaType.APPLICATION_JSON)
//        supportedMediaTypes.add(ActuatorMediaTypes)
            supportedMediaTypes.add(MediaType.TEXT_PLAIN)
            val converter = MappingJackson2HttpMessageConverter()
            val objectMapper = ApplicationJsonObjectMapper()

            converter.objectMapper = objectMapper
            converter.setPrettyPrint(true)
            converter.supportedMediaTypes = supportedMediaTypes

            restTemplate.messageConverters.add(0, converter)
            return restTemplate
        }
    }
}
package com.umh.medicalbookingplatform.core.utils

import io.netty.channel.ChannelOption
import io.netty.handler.timeout.ReadTimeoutHandler
import io.netty.handler.timeout.WriteTimeoutHandler
import org.springframework.http.MediaType
import org.springframework.http.client.reactive.ReactorClientHttpConnector
import org.springframework.http.codec.ClientCodecConfigurer
import org.springframework.http.codec.json.Jackson2JsonDecoder
import org.springframework.http.codec.json.Jackson2JsonEncoder
import org.springframework.web.reactive.function.client.ExchangeStrategies
import org.springframework.web.reactive.function.client.WebClient
import reactor.netty.http.client.HttpClient
import java.time.Duration


class WebClientUtils {

    companion object {
        fun getWebClient(timeOutTime: Int? = null): WebClient {


            val httpClient = HttpClient.create()
//                .responseTimeout(Duration.ofSeconds(timeOutTime?.toLong() ?: (5 * 60)))
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000)
                .doOnConnected { connection ->
                    connection
                        .addHandlerLast(ReadTimeoutHandler(timeOutTime ?: (5 * 60)))
                        .addHandlerLast(WriteTimeoutHandler(timeOutTime ?: (5 * 60)))
                }

            val strategies = ExchangeStrategies
                .builder()
                .codecs { clientDefaultCodecsConfigurer: ClientCodecConfigurer ->
                    clientDefaultCodecsConfigurer.defaultCodecs()
                        .jackson2JsonEncoder(
                            Jackson2JsonEncoder(
                                ApplicationJsonObjectMapper(),
                                MediaType.APPLICATION_JSON
                            )
                        )
                    clientDefaultCodecsConfigurer.defaultCodecs()
                        .jackson2JsonDecoder(
                            Jackson2JsonDecoder(
                                ApplicationJsonObjectMapper(),
                                MediaType.APPLICATION_JSON
                            )
                        )
                    clientDefaultCodecsConfigurer.defaultCodecs()
                        .maxInMemorySize(16 * 1024 * 1024)
                }.build()


            return WebClient.builder()
                .clientConnector(ReactorClientHttpConnector(httpClient))
                .exchangeStrategies(strategies)
                .build()
        }
    }
}
//        val headers = HttpHeaders()
//        headers.set("Accept", "application/json")
//        headers.set("version", "v1")
//        headers.set("x-umhappweb-authorization", keycloakGlobalCmsApi.tokenManager().accessToken.token)
//        val entity = HttpEntity(null, headers)
        val apiCmsInvokeUri =
            UriComponentsBuilder.fromHttpUrl(applicationProperties.globalCmsApiEndpoint + "/v1/api/specialty_list")
                .queryParam("get_type", "")
                .queryParam("channel_id", "4")
                .queryParam("state", "2")
                .toUriString()
        val response: Any?
        try {
            logger.info("[START] Call globalcms '$apiCmsInvokeUri'")
//            response = RestTemplateUtils.getRestTemplate().exchange(
//                    UriComponentsBuilder.fromHttpUrl(applicationProperties.globalCmsApiEndpoint + apiCmsInvokeUri)
//                            .queryParam("get_type", "")
//                            .queryParam("channel_id", "4")
//                            .queryParam("state", "2")
//                            .toUriString(),
//                    HttpMethod.GET,
//                    entity,
//                    Object::class.java,
//            )
            response = WebClientUtils.getWebClient()
                .method(HttpMethod.GET)
                .uri(apiCmsInvokeUri)
                .header("Accept", "application/json")
                .header("version", "v1")
                .header("x-umhappweb-authorization", keycloakGlobalCmsApi.tokenManager().accessToken.token)
                //                .body(Mono.just(param), UmhBookingParam::class.java)
                .retrieve()
                .bodyToMono(object : ParameterizedTypeReference<Any?>() {})
                .block()
            logger.info("[END] Call globalcms '$apiCmsInvokeUri'")
        } catch (e: WebClientResponseException) {
            logger.error(e.responseBodyAsString, e)
            throw ApplicationException(ErrorCode.ERR_GLOBAL_CMS_SPECIALTIES_API)
        }

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值