Hi guys, I was wondering if there exist something ...
# android
m
Hi guys, I was wondering if there exist something for JSON parsing that work with Retrofit in android like Codable Protocol in ios Swift that allow dynamic json parsing ,or I should create my own JSON converter for every type?
c
There’s a Retrofit converter adapter for kotlinx.serialization https://github.com/JakeWharton/retrofit2-kotlinx-serialization-converter
m
Thanks, will try it
a
Gson and it has a converter factory for retrofit
c
Moshi has been nice, you forget there’s even JSON serialization happening
v
I also prefer Moshi over Gson because Moshi gives an exception when you try to parse null/absent values into fields that are non-nullable. Gson silently sets those non-nullable fields to null via reflection and then you get an exception where you won't expect it.
m
Yes I had tried Converter factory but this will reqire me to know all the keys which valus are changing , lets say for example I have a key which return sometimes JsonArray and other times return JsonObject in the same API Call ,so I need to know this key
v
@Mohammed Alaa Can you post samples of the type of responses you are expecting?
m
c
Oh gotcha. So as other countries are added you’ll get a new key and value but the root object would stay the same?
m
@Cody Engel yes
a
I had the same issue that the same key could be either an array or an object and successfully fixed it with Gson
Also if you are using kotlin and null is set to non-nullable value the app will crash
Pretty common case it seems 🤷
m
@Anastasia Finogenova Thanks, this is very interesting
@Anastasia Finogenova👍 Solution with Generic are good for me so I can't know how many keys will need this
💯 1
c
This shouldn’t be a common use case but yeah it happens. Moshi lets you write custom converters as well.
💯 1
a
Common in a way it doesn't surprise me at all😅
😂 3
m
@Cody Engel yes it isn't a common use case but it happened with me 😃
a
Happened to me too and appearantly if the answer on stackoverflow has 74 upvotes at least to other 74 people 😆
m
Yes, You count only who up-vote so whats about others who doesn't vote and happened with them 😉
a
Exactly, some bad backend designers out there 🤷
c
For sure, don’t want to say it doesn’t happen regularly with various APIs, just saying that it shouldn’t because an array and map aren’t the same type 😂
But with Moshi you can create custom adapters with the
@FromJson
annotation probably similar to other JSON serialization libraries; because while it shouldn’t be normal it unfortunately is normal enough lol