1. Mental model of JSON and XML
Honestly, a developer rarely wakes up in the morning thinking: “Should I compare JSON and XML today before my coffee gets cold?” Usually the format choice happens because someone else has already made half the decision for you: an external service returns XML, an old corporate API requires SOAP, accounting sends a “magnificent” XML file, and your project, on the contrary, wants a simple report in JSON. And there you are standing between two worlds: the compact “data as structure” world (JSON) and the more “document-like” world of tags (XML).
It’s important to understand: JSON and XML are not “better/worse” — they are different data representation models. And if you choose a format without criteria, you can easily end up in a situation where data seems to be transmitted, but every next development step starts to feel like the quest “guess where we lost the types / order / nesting / escaping”.
To choose a format consciously, it helps to first agree on how we even mentally “see” data in each format. It’s like choosing a food container: soup in a bag is technically possible, but you don’t have to suffer like that. JSON and XML answer the question “what is a data structure?” differently, and that directly affects how easy it will be for us to read, validate, and generate this data in Kotlin.
JSON as a tree of values
JSON is a tree where nodes come in four main types: object (key-value pairs), array (an ordered list), primitive (string/number/boolean), and null. In previous lectures, we literally worked with this as a JsonElement tree, and that feeling is very accurate: each node is a value that has a type, and the type can be checked.
Practical effect: if you see true or 123 in JSON, you already understand that it’s a boolean and a number (even though sometimes you still have to convert from a string if the data is “dirty”).
XML as a tree of document elements
XML is also a tree, but the nodes are elements (tags) with names, attributes, and text content. And this is where the philosophy begins: historically, XML grew as a document format where markup, nesting, and tag meaning matter, not the “value type” as such.
Practical effect: almost everything in XML, by its nature, looks like strings (text inside an element or an attribute value). You add typing by “convention”: for example, <age>21</age> is a number only because you decided so and your code parsed it that way.
3. Data vs document
In real projects, the most useful question sounds like this: are you transmitting data (a structure for a program) or a document (text with markup, where elements, attributes, order, and sometimes mixed content matter)? This is not “pure theory” — it’s a fast way to stop arguing in the style of “JSON is trendy, XML is old” and start choosing a format for the task.
JSON usually wins when you describe “here is an object, it has fields, the field has a type, sometimes an array”. This is a typical format for APIs, configs, reports, and data exchange between services.
XML often wins when you describe “here is a document, it has structure, elements, metadata in attributes, sometimes order matters, sometimes namespaces matter”. This is a typical format for document workflows, some integrations, old standards, and, in general, a world where “tags” matter more than “types”.
4. Comparison by criteria
Below is a practical criteria table. This isn’t “the ultimate truth”, but a good checklist that really helps you make a decision and then not regret it.
| Criterion | JSON | XML | What it means for Kotlin code |
|---|---|---|---|
| Readability for “data” | Usually simpler and shorter | Usually more verbose | JSON is faster to read with your eyes and easier to generate |
| Primitive “types” | Types are visible (true, 123, "text", null) | Everything looks like text | With JSON there is less “guessing types”; with XML parsing is almost always manual/rule-based |
| Arrays/lists | Natural [...] | Done via repeated tags | In JSON it’s easier to express “a list of same-kind things” |
| Attributes as a separate concept | No (everything is fields) | Attributes exist | XML conveniently stores “metadata” next to the element |
| Order | Matters in arrays; usually not in objects | Element order is often treated as important | If order is meaningful as part of the semantics, XML can feel more natural |
| Comments | Strict JSON doesn’t have them | XML has comments | For “human” configs, XML is sometimes more convenient (but it’s a double-edged sword) |
| Schemas/validation | Approaches exist, but often “by convention” | Historically a strong schema ecosystem | If you have strict standards and contracts, the XML world is often more “regulated” |
| Size/noise | Usually smaller | Usually larger | For logs/network responses, JSON is more efficient in size |
| Integrations | Very common in modern APIs | Very common in old/corporate standards | The choice is often dictated by the external environment |
A small real-life observation: Kotlin tooling and the ecosystem like JSON because it’s a convenient format for machine reports. For example, the migration documentation for K2 mentions saving build reports in JSON format, meaning JSON is actually used as a “machine-readable report”.
5. The same meaning in JSON and XML
Comparing formats without examples is like explaining swimming from a book: technically possible, but better not. Let’s take the same meaning and write it in two ways. Suppose we have a user and their tags.
Example data
- user: id=1, name="Alice"
- tags: ["kotlin", "json"]
JSON version
fun main() {
val json = """{"user":{"id":1,"name":"Alice"},"tags":["kotlin","json"]}"""
println(json) // {"user":{"id":1,"name":"Alice"},"tags":["kotlin","json"]}
}
Here an array is an array, numbers are numbers, strings are strings. No surprises: the structure is very close to Kotlin data structures (Map/List/primitives).
XML version
fun main() {
val xml = """
<root>
<user>
<id>1</id>
<name>Alice</name>
</user>
<tags>
<tag>kotlin</tag>
<tag>json</tag>
</tags>
</root>
""".trimIndent()
println(xml)
}
XML looks more “document-like”: lots of tags, explicit hierarchy, repeated elements for a list. And note: the number 1 here is text "<id>1</id>". That it is an Int will be known only to your parser (or your validation).
6. Typing and attributes
Typing and why in XML everything suddenly becomes a string
If you’ve ever caught the bug “why is age 21 compared as a string and it turns out that 9 is ‘greater’ than 21”, then you already intuitively understand why typing matters. JSON helps because primitives are typed at the format level. XML leaves typing to the conscience of convention and the code that reads the document.
Practical effect #1: validation is needed in any format
Both JSON and XML can be “syntactically correct” but “logically garbage”. We already talked about this for JSON: parseToJsonElement() answers only “is this valid JSON?”, but not “do these values work for us?” With XML it’s similar: even if XML is well-formed, it can contain empty fields, invalid ranges, unexpected elements.
Practical effect #2: in XML you write conversions more often
In XML you almost always do String -> Int? / String -> Boolean? yourself. In JSON this also happens (especially if the data is “dirty”), but by default the types are at least closer to what you expect.
XML attributes: power and a source of endless arguments
Attributes are one of the reasons XML is still alive and not planning to “retire to a museum of ancient technologies”. Attributes let you store metadata right on the element. This is convenient, but it also creates “religious wars”: what should be an attribute and what should be an element?
Let’s compare two variants of the same meaning:
fun main() {
val xmlWithAttribute = """<user id="1"><name>Alice</name></user>"""
val xmlWithElement = """<user><id>1</id><name>Alice</name></user>"""
println(xmlWithAttribute) // <user id="1"><name>Alice</name></user>
println(xmlWithElement) // <user><id>1</id><name>Alice</name></user>
}
In JSON there is almost no such choice: you would just do "id": 1. And that’s a plus: fewer options means less confusion in data and code.
7. Where JSON and XML fit in Kotlin projects
Where JSON is especially good in our course
We have already built reports, aggregated data, and made pipelines “took a collection → computed → formed a result”. And for such tasks, JSON is an almost perfect “container for the result”: it’s convenient to assemble manually, convenient to save, convenient to send as a structure.
By the way, in the Kotlin ecosystem, serialization is not “exotic” but a stable tool: the Kotlin component stability table explicitly mentions kotlinx-serialization as a stable library.
Mini example: a JSON report for our expense tracker
Let’s imagine that in our practical app (conditionally “Expense Tracker”) we calculate total expenses and want to produce a report.
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.buildJsonObject
data class Expense(val title: String, val amount: Int)
fun buildReport(expenses: List<Expense>): JsonObject {
val total = expenses.sumOf { it.amount }
return buildJsonObject {
put("total", JsonPrimitive(total))
put("count", JsonPrimitive(expenses.size))
}
}
fun main() {
val expenses = listOf(
Expense("Coffee", 5),
Expense("Pizza", 12),
)
val report = buildReport(expenses)
println(report) // {"total":17,"count":2}
}
Notice how naturally this fits Kotlin collections: we computed numbers and put them into JSON as numbers, without losing types along the way.
Where XML may be more appropriate
Sometimes choosing “XML” is not because you want an adventure, but because you are connecting to a world where XML is already the standard. These can be documents, integration formats, industry standards, or sometimes simply “that’s how it’s historically done”.
In the Kotlin/JVM world, XML often goes hand in hand with Java libraries and standard APIs. Even in Kotlin changes you can see mentions of infrastructure related to org.w3c (a family of interfaces historically associated with the XML DOM model).
But the key point: with XML, more often you need to agree in advance on “representation rules”. For example, how do we encode a list: repeated tags? a separate container <items>? what do we name elements? This is not bad; it’s just a different style.
8. Validation and generation: how not to break a project
Format is not business rules
An important point that often breaks projects: people think that if the format is chosen “correctly”, then validation is no longer needed. Unfortunately, the format is only syntax and basic structure.
We already built an Ok/Error layer for JSON validation. And here is a good habit: regardless of whether you have JSON or XML, keep the same architecture in mind:
flowchart TD
A["Text (JSON or XML)"] --> B["Parsing: 'is it even a valid format?'"]
B --> C["Validation: 'does the data match the application's rules?'"]
C --> D["Domain model / calculations / reports"]
This diagram saves you from the typical pain: “it sometimes crashes in prod” because someone sent a valid file, but with an empty id or a negative amount.
A quick algorithm for choosing a format
Sometimes you want a simple rule so you don’t argue forever. Let this be not a rule but a short decision-making algorithm that works pretty well in most learning and practical tasks.
First, answer the question: is the data structure stable or not? If the structure is unstable, for JSON you have an excellent tool — the JsonElement tree and safe extraction.
Next, ask: do you care more about “data as object/array” or “document as markup”? If data matters more, JSON is chosen more often. If “document-ness”, standards, and compatibility with existing XML contracts matter more — XML.
And finally, the most real criterion: who is your “integration neighbor”? If the outside world returns XML, you won’t beat reality with a motivational speech about JSON — you will read XML. If the outside world speaks JSON, you will work with JSON.
Mini nuance: don’t concatenate strings
This is a small piece of advice from the category “everyone steps on rakes, but you can at least wear soft slippers”. If you generate JSON, try to build it as a structure (buildJsonObject, buildJsonArray), rather than concatenating strings.
In Kotlin documentation about idioms, even in a Gson example, JsonElement is shown as a “universal carrier of JSON structure” that can then be converted into the required type. It’s the same idea as in our kotlinx.serialization.json: first structure, then (if needed) string.
With XML, it’s a similar story: if you don’t use a library, then “string concatenation” becomes almost inevitable, but then escaping and care become especially important. And yes, this is exactly the moment when the program starts taking revenge for “good enough”.
9. Typical mistakes when choosing and using JSON/XML
Mistake #1: thinking that “if it parsed, it’s correct”.
Both JSON and XML can be syntactically correct while containing values that are meaningless for your program. For example, id = -10, an empty name, an expense amount of 0 where it must not be zero. Therefore, a validation layer is not an “extra option” but a mandatory part of design: parsing is responsible for shape, validation is responsible for meaning.
Mistake #2: confusing “field missing” and “field present but empty/null”.
In JSON we have already seen the difference between “no field” and “value null”. In XML the same problem shows up differently: the element may be missing, the element may be empty (<name></name>), the element may be self-closing (<name/>), and that often means different things. If you don’t agree on semantics, you’ll get a bunch of weird if.
Mistake #3: expecting types to come “by themselves” in XML.
In JSON, primitive types are visible immediately, while in XML almost everything looks like a string. Beginners often write code as if <age>21</age> is “already a number” and compare it as a string, or forget to handle a non-numeric value. In XML, you need to plan safe conversions and error messages in advance; otherwise, the data will “break” your scenario at the worst possible moment.
Mistake #4: uncontrolled mixing of attributes and elements in XML.
When some developers put id into an attribute (<user id="1">), and others put it into an element (<id>1</id>), you end up with two “subformats” inside one format. Then someone writes a parser for one variant, and the data arrives in the other. The result is a bug that looks like “sometimes it doesn’t work”, i.e., the most annoying kind of bug.
Mistake #5: building JSON/XML via “string concatenation” and then wondering why everything breaks.
String concatenation almost guarantees mistakes: you forgot a comma in JSON, didn’t escape & or < in XML, accidentally added an extra newline, and that’s it — the parser is unhappy, the user is unhappy, and you are unhappy with life. If you can build JSON as a tree, do it. For XML it’s better to aim for structural construction too, but within this lecture we at least fix the problem: string-based construction is fragile.
Mistake #6: choosing a format “because you like it” instead of because it fits the task.
Liking JSON is fine. Liking XML is also fine (as long as it doesn’t become your only personality trait). But formats are chosen by criteria: what the integration dictates, what is easier to validate, where order matters, where compactness is needed, who will read the data — a human or a program. If the criteria are not discussed, the decision usually turns out random, and the cost of randomness is the team’s time and the product’s quality.
GO TO FULL VERSION