What is JSON format used for?
We've seen how to work with objects, we can create, edit or pass objects as a parameter inside our project, but if we need to send/receive them from a server we need to do this in a format that any system can understand. We can convert any object into a single String
following an universal format called JSON, that any system in the world will understand.
Later, we will see how to automate this conversion, but for now, let's look at an example of to convert an object called Person into a JSONs.
struct Person {
var name: String
var age: Int
}
var client = Person(name: "Pablo", age: 23)
If we converted our client
variable value into a JSON, we would get a String like this.
{"name":"Pablo","age":23}
Which we can view more clearly in this format.
{
"name": "Pablo",
"age": 23
}
The rules of JSON format
For anyone receiving this String to be able to interpret what it is, this format must strictly follow a set of rules.
- It must start and end with
{
and}
, unless it's an array, which we will see in the next section. - Everything except numbers must be enclosed in quotes.
- Key-value pairs, separated by a colon. Key is the variable name, and the value is the value of it.
- Key-value pairs must be separated by commas.
Arrays
Let's imagine we want to send or receive a list of clients in JSON format. We can have several clients, enclosed in square brackets and separated by commas.
[
{
"name": "Pablo",
"age": 23
},
{
"name": "Pedro",
"age": 25
},
{
"name": "Andrea",
"age": 28
}
]
Each client follows the format we saw in the previous section.
Nesting parameters
With the rules we've just seen, we can create any combination, even nesting parameters (i.e., placing some inside others).
Let's see an example of a list of posts where each Post
object has a User
object inside.
struct User {
let name: String
let imageName: String
}
struct Post {
let user: User
let date: String
let text: String
let imageName: String
}
[
{
"user": {
"name": "Pablo",
"age": 35
},
"text": "Post text...",
"image": "https://postImageUrl.com"
},
{
"user": {
"name": "Andrea",
"age": 33
},
"text": "Post text...",
"image": "https://postImageUrl.com"
}
]
As you can see, you can nest endless objects as long as you always follow the same rules.
As a last example let's see a very common JSON format response from a server where not only we get the info we need to show but also some extra info:
{
"code": 200,
"posts": [
{
"user": {
"name": "Pablo",
"age": 35
},
"text": "Post text...",
"image": "https://postImageUrl.com"
},
{
"user": {
"name": "Andrea",
"age": 33
},
"text": "Post text...",
"image": "https://postImageUrl.com"
}
]
}
We often get some info about the request next to the response we asked for, like the response code. A 200 code just means that everything went well, but the important point here is that all our posts are wrapped inside "posts" field. We'll see in upcoming articles how to convert objects to JSON strings and vice versa.
Be the first to comment