Guest User

Untitled

a guest
Feb 25th, 2018
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.45 KB | None | 0 0
  1. import com.google.gson.*
  2. import java.math.BigDecimal
  3. import java.math.BigInteger
  4.  
  5. /**
  6. * Created by Terence Baker on 13/02/2018.
  7. */
  8.  
  9. val JsonElement.optString: String?
  10. get() = safeConversion { asString }
  11.  
  12. val JsonElement.optLong: Long?
  13. get() = safeConversion { asLong }
  14.  
  15. val JsonElement.optBoolean: Boolean?
  16. get() = safeConversion { asBoolean }
  17.  
  18. val JsonElement.optFloat: Float?
  19. get() = safeConversion { asFloat }
  20.  
  21. val JsonElement.optDouble: Double?
  22. get() = safeConversion { asDouble }
  23.  
  24. val JsonElement.optJsonObject: JsonObject?
  25. get() = safeConversion { asJsonObject }
  26.  
  27. val JsonElement.optJsonArray: JsonArray?
  28. get() = safeConversion { asJsonArray }
  29.  
  30. val JsonElement.optJsonPrimitive: JsonPrimitive?
  31. get() = safeConversion { asJsonPrimitive }
  32.  
  33. val JsonElement.optInt: Int?
  34. get() = safeConversion { asInt }
  35.  
  36. val JsonElement.optBigDecimal: BigDecimal?
  37. get() = safeConversion { asBigDecimal }
  38.  
  39. val JsonElement.optBigInteger: BigInteger?
  40. get() = safeConversion { asBigInteger }
  41.  
  42. val JsonElement.optByte: Byte?
  43. get() = safeConversion { asByte }
  44.  
  45. val JsonElement.optShort: Short?
  46. get() = safeConversion { asShort }
  47.  
  48. val JsonElement.optJsonNull: JsonNull?
  49. get() = safeConversion { asJsonNull }
  50.  
  51. val JsonElement.optCharacter: Char?
  52. get() = safeConversion { asCharacter }
  53.  
  54. private fun <T> JsonElement.safeConversion(converter: () -> T?): T? {
  55.  
  56. return try {
  57. converter()
  58. }
  59. catch (e: Exception) {
  60. null
  61. }
  62. }
Add Comment
Please, Sign In to add comment