0
0
Android Kotlinmobile~15 mins

JSON parsing with Gson/Moshi in Android Kotlin - Deep Dive

Choose your learning style9 modes available
Overview - JSON parsing with Gson/Moshi
What is it?
JSON parsing with Gson or Moshi means converting JSON text into Kotlin objects and back. JSON is a common format to send data between apps and servers. Gson and Moshi are libraries that help Android apps read and write JSON easily without manual work.
Why it matters
Without JSON parsing libraries, developers would have to write complex code to read and write JSON strings manually, which is slow and error-prone. These libraries save time and prevent bugs, making apps faster to build and more reliable when handling data from the internet.
Where it fits
Before learning JSON parsing, you should understand Kotlin basics and how data classes work. After this, you can learn about networking libraries like Retrofit that use Gson or Moshi to handle JSON automatically.
Mental Model
Core Idea
JSON parsing libraries automatically convert between JSON text and Kotlin objects so you can work with data naturally in your app.
Think of it like...
Imagine JSON as a letter written in a foreign language, and Gson or Moshi as a translator who reads the letter and writes it in your native language so you understand it easily.
JSON Text <--> [Gson/Moshi] <--> Kotlin Objects

┌─────────────┐       ┌───────────────┐       ┌───────────────┐
│ JSON String │  <--->│ Gson or Moshi │ <---> │ Kotlin Object │
└─────────────┘       └───────────────┘       └───────────────┘
Build-Up - 7 Steps
1
FoundationUnderstanding JSON format basics
🤔
Concept: Learn what JSON looks like and how it represents data with keys and values.
JSON is a text format that uses curly braces { } for objects and square brackets [ ] for lists. Data is stored as key-value pairs, like "name": "Alice" or "age": 30. It is easy for humans to read and machines to parse.
Result
You can recognize JSON strings and understand their structure.
Knowing JSON structure helps you see why parsing is needed to convert text into usable data.
2
FoundationKotlin data classes for JSON data
🤔
Concept: Use Kotlin data classes to represent the structure of JSON data in your app.
Define a data class with properties matching JSON keys. For example, data class User(val name: String, val age: Int) matches JSON {"name": "Alice", "age": 30}. This class will hold parsed data.
Result
You have a Kotlin blueprint that matches the JSON data shape.
Mapping JSON to data classes makes your code clear and type-safe.
3
IntermediateParsing JSON with Gson library
🤔Before reading on: do you think Gson requires manual parsing code for each field or does it automate the process? Commit to your answer.
Concept: Gson automatically converts JSON strings into Kotlin objects and vice versa using reflection.
Create a Gson instance and call gson.fromJson(jsonString, User::class.java) to get a User object. To convert back, use gson.toJson(user). Gson matches JSON keys to data class properties by name.
Result
You can convert JSON text to Kotlin objects with one line of code.
Understanding Gson's automation saves you from writing error-prone manual parsing.
4
IntermediateParsing JSON with Moshi library
🤔Before reading on: do you think Moshi uses the same approach as Gson or a different method to parse JSON? Commit to your answer.
Concept: Moshi uses code generation or reflection to parse JSON efficiently and supports Kotlin features better than Gson.
Create a Moshi instance and get an adapter: val adapter = moshi.adapter(User::class.java). Then call adapter.fromJson(jsonString) to parse. Moshi handles nullability and default values more safely.
Result
You can parse JSON with Moshi, benefiting from Kotlin-friendly features.
Knowing Moshi's Kotlin support helps you choose the best tool for your app.
5
IntermediateHandling nested JSON objects
🤔Before reading on: do you think nested JSON requires special parsing code or can Gson/Moshi handle it automatically? Commit to your answer.
Concept: Gson and Moshi can parse nested JSON by nesting data classes accordingly.
If JSON has nested objects like {"user": {"name": "Alice", "age": 30}}, define data classes: data class Response(val user: User) and data class User(val name: String, val age: Int). Parsing Response will parse nested User automatically.
Result
You can parse complex JSON structures with nested objects easily.
Understanding nested data classes unlocks handling real-world JSON data.
6
AdvancedCustomizing parsing with annotations
🤔Before reading on: do you think JSON keys must always match Kotlin property names exactly? Commit to your answer.
Concept: Use annotations to map JSON keys to different Kotlin property names or handle special cases.
Gson uses @SerializedName("json_key") and Moshi uses @Json(name = "json_key") to map JSON keys to properties with different names. This helps when JSON keys are not valid Kotlin names or differ from your code style.
Result
You can parse JSON even when keys and property names differ.
Knowing how to customize key mapping prevents bugs with mismatched names.
7
ExpertPerformance and error handling in parsing
🤔Before reading on: do you think Gson and Moshi handle all JSON errors the same way or differently? Commit to your answer.
Concept: Gson and Moshi differ in performance and error handling; Moshi is generally faster and safer with Kotlin nullability.
Gson uses reflection which can be slower and less safe with Kotlin nulls. Moshi supports code generation for faster parsing and better null safety. Both throw exceptions on malformed JSON, but Moshi's errors are often clearer. You can add custom adapters for special types or error recovery.
Result
You understand tradeoffs and can optimize parsing for production apps.
Knowing internal differences helps you pick the right library and write robust code.
Under the Hood
Both Gson and Moshi parse JSON by reading the text and matching keys to Kotlin properties. Gson uses reflection at runtime to inspect classes and set fields dynamically. Moshi can use reflection or generate code at compile time for faster parsing. They convert JSON tokens into Kotlin values, handling types like strings, numbers, lists, and nested objects.
Why designed this way?
Reflection allows Gson to work without extra setup but can be slow and error-prone with Kotlin features. Moshi was designed to improve on Gson by using code generation for speed and better Kotlin support, especially null safety and default values. Both aim to simplify JSON handling compared to manual parsing.
JSON Text
   │
   ▼
┌───────────────┐
│  Parser Core  │
│ (Gson/Moshi)  │
└───────────────┘
   │
   ▼
┌───────────────┐
│ Reflection or │
│ Code Gen for  │
│  Kotlin Types │
└───────────────┘
   │
   ▼
┌───────────────┐
│ Kotlin Object │
└───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Do you think Gson automatically handles Kotlin nullability perfectly? Commit yes or no.
Common Belief:Gson fully supports Kotlin null safety and default values without extra work.
Tap to reveal reality
Reality:Gson does not handle Kotlin nullability or default parameters well, often causing crashes or requiring workarounds.
Why it matters:Ignoring this leads to runtime crashes or incorrect data when parsing JSON with missing or null fields.
Quick: Do you think you must write manual parsing code for every JSON structure? Commit yes or no.
Common Belief:You have to write code to parse each JSON field manually.
Tap to reveal reality
Reality:Gson and Moshi automate parsing by matching JSON keys to data class properties, so manual parsing is rarely needed.
Why it matters:Believing this wastes time and effort reinventing parsing logic.
Quick: Do you think Gson and Moshi are interchangeable with no differences? Commit yes or no.
Common Belief:Gson and Moshi work exactly the same and can be swapped without changes.
Tap to reveal reality
Reality:They differ in performance, Kotlin support, and customization options, so choice affects app behavior and speed.
Why it matters:Choosing the wrong library can cause bugs or slow app performance.
Quick: Do you think JSON keys must always match Kotlin property names exactly? Commit yes or no.
Common Belief:JSON keys and Kotlin property names must be identical for parsing to work.
Tap to reveal reality
Reality:Annotations let you map different JSON keys to Kotlin properties easily.
Why it matters:Not knowing this causes parsing failures or incorrect data mapping.
Expert Zone
1
Moshi's code generation can reduce app size and improve startup time compared to Gson's reflection.
2
Custom adapters in Moshi allow parsing complex or non-standard JSON formats that Gson struggles with.
3
Handling polymorphic JSON objects (different types in one field) requires advanced adapter setup, which Moshi supports better.
When NOT to use
Avoid Gson or Moshi when working with extremely large JSON files needing streaming parsing; use streaming APIs like JsonReader instead. For very simple JSON, manual parsing might be faster. Also, if you need full control over parsing errors or partial data recovery, custom parsers may be better.
Production Patterns
In production, Moshi is often paired with Retrofit for network calls, using code generation for speed. Gson is still used in legacy projects or when reflection is acceptable. Custom adapters handle date formats, enums, or polymorphic types. Error handling wraps parsing calls to catch malformed JSON gracefully.
Connections
Networking with Retrofit
Builds-on
Understanding JSON parsing is essential because Retrofit uses Gson or Moshi to convert server responses into Kotlin objects automatically.
Kotlin Null Safety
Builds-on
Knowing Kotlin's null safety helps you understand why Moshi handles JSON parsing more safely than Gson, preventing null-related crashes.
Data Serialization in Distributed Systems
Same pattern
JSON parsing with Gson/Moshi is a form of data serialization, a concept used in many fields like databases and networking to convert data between formats.
Common Pitfalls
#1Parsing JSON without matching data class structure
Wrong approach:val user = gson.fromJson(jsonString, User::class.java) // but User class missing some JSON fields
Correct approach:Define User data class with all expected JSON fields or mark optional fields nullable.
Root cause:Mismatch between JSON structure and Kotlin data class causes parsing errors or missing data.
#2Ignoring nullability in Kotlin data classes
Wrong approach:data class User(val name: String, val age: Int) // but JSON might have null age
Correct approach:data class User(val name: String, val age: Int?) // age nullable to match JSON
Root cause:Not accounting for nullable JSON fields leads to runtime exceptions.
#3Using Gson without @SerializedName for mismatched keys
Wrong approach:data class User(val userName: String) // JSON key is "user_name" but no annotation
Correct approach:data class User(@SerializedName("user_name") val userName: String)
Root cause:JSON keys and Kotlin property names differ, causing parsing to fail silently.
Key Takeaways
JSON parsing libraries like Gson and Moshi convert JSON text into Kotlin objects automatically, saving time and reducing errors.
Kotlin data classes should match the JSON structure closely, including nullability and nested objects, for smooth parsing.
Moshi offers better Kotlin support and performance through code generation compared to Gson's reflection approach.
Annotations let you map JSON keys to different Kotlin property names, solving common mismatches.
Understanding parsing internals and differences helps you choose the right library and write robust, maintainable Android apps.