All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.autonomousapps.internal.utils.moshi.kt Maven / Gradle / Ivy

There is a newer version: 2.0.2
Show newest version
@file:JvmName("MoshiUtils")

package com.autonomousapps.internal.utils

import com.squareup.moshi.FromJson
import com.squareup.moshi.JsonAdapter
import com.squareup.moshi.Moshi
import com.squareup.moshi.ToJson
import com.squareup.moshi.Types.newParameterizedType
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import java.io.File

val MOSHI: Moshi by lazy {
  Moshi.Builder()
    .add(DependencyGraphAdapter())
    .add(KotlinJsonAdapterFactory())
    .add(TypeAdapters())
    .build()
}

inline fun  getJsonAdapter(withNulls: Boolean = false): JsonAdapter {
  val adapter = MOSHI.adapter(T::class.java)
  return if (withNulls) {
    adapter.serializeNulls()
  } else {
    adapter
  }
}

inline fun  getJsonListAdapter(withNulls: Boolean = false): JsonAdapter> {
  val type = newParameterizedType(List::class.java, T::class.java)
  val adapter = MOSHI.adapter>(type)
  return if (withNulls) {
    adapter.serializeNulls()
  } else {
    adapter
  }
}

inline fun  getJsonSetAdapter(withNulls: Boolean = false): JsonAdapter> {
  val type = newParameterizedType(Set::class.java, T::class.java)
  val adapter = MOSHI.adapter>(type)
  return if (withNulls) {
    adapter.serializeNulls()
  } else {
    adapter
  }
}

inline fun  getJsonMapAdapter(withNulls: Boolean = false): JsonAdapter> {
  val type = newParameterizedType(Map::class.java, K::class.java, V::class.java)
  val adapter = MOSHI.adapter>(type)
  return if (withNulls) {
    adapter.serializeNulls()
  } else {
    adapter
  }
}

inline fun  String.fromJson(): T {
  return getJsonAdapter().fromJson(this)!!
}

inline fun  T.toJson(withNulls: Boolean = false): String {
  return getJsonAdapter(withNulls).toJson(this)
}

inline fun  String.fromJsonList(withNulls: Boolean = false): List {
  return getJsonListAdapter(withNulls).fromJson(this)!!
}

inline fun  String.fromJsonSet(withNulls: Boolean = false): Set {
  return getJsonSetAdapter(withNulls).fromJson(this)!!
}

inline fun  String.fromJsonMapList(): Map> {
  val listType = newParameterizedType(List::class.java, V::class.java)
  val mapType = newParameterizedType(Map::class.java, K::class.java, listType)
  val adapter = MOSHI.adapter>>(mapType)

  return adapter.fromJson(this)!!
}

inline fun  T.toPrettyString(withNulls: Boolean = false): String {
  return getJsonAdapter(withNulls).indent("  ").toJson(this)
}

inline fun  Map.toPrettyString(withNulls: Boolean = false): String {
  return getJsonMapAdapter(withNulls).indent("  ").toJson(this)
}

@Suppress("unused", "HasPlatformType")
internal class TypeAdapters {

  @ToJson fun fileToJson(file: File) = file.absolutePath
  @FromJson fun fileFromJson(absolutePath: String) = File(absolutePath)
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy