T
T
Tsuzukeru2021-03-24 19:39:24
Android
Tsuzukeru, 2021-03-24 19:39:24

How to add Json parsing logic without using a deserializer?

I use Retrofit to work with Rest API.
I know that Gson contains annotations that can be used to pull the data we need from Json, but what if this data needs to be preprocessed?
For example, I need to format a date received from Json. To do this, I use the following code in the deserializer ( and this is only for one field out of 10 ):

dataValue.entrySet()?.forEach { 
    if (it.key == "date_created") {
        Log.i(TAG, "date_created exists")

        val dateStr: String = it.value.asString
        val parsedDateFormat =
            SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX")

        val parsedDate: Date = parsedDateFormat.parse(dateStr)

        val dayDateFormat = SimpleDateFormat("dd")
        val day = dayDateFormat.format(parsedDate)

        val monthDateFormat = SimpleDateFormat("MMMM")
        val month = monthDateFormat.format(parsedDate)

        val yearDateFormat = SimpleDateFormat("yyyy")
        val year = yearDateFormat.format(parsedDate)

        dateCreated = "$month $day, $year"
}


As a result, the deserializer code turns out to be quite cumbersome and difficult to read. I want to get rid of it and use annotations. But how can they be used to solve such problems? It comes to mind to create additional fields with lazy initialization, which will pull the raw fields and convert them to the desired format, but then the class will contain a lot of unnecessary information and methods. Are there better ways?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2021-03-24
@Tsuzukeru

Yes, I have. it is not necessary to keep the formatted fields in the data. It is necessary to format immediately before use (for example, display in a view). To do this, there must be a separate layer that handles the formatting of all data for display (and this can be not only text formatting).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question