Oh that’s interesting. There is no system API that will take a JSON value like this and serialise it to the binary DNS message format. You’ll need to write or acquire your own code for that. That involves two steps:
-
Parsing the JSON to some sort of model-level value.
-
Rendering that model value into the binary DNS message format.
The first is relatively straightforward for the data you posted. I’ve included a snippet below.
IMPORTANT This only works on the data you posted. DNS messages have a lot of flexibility and, if your server sends you JSON in some other folks, you’ll need to adapt the code accordingly.
If you decide to write your own code for the second step, that’s significantly harder. You have to understanding the binary DNS message format. You can find a high-level summary here but I think you’re eventually going to want to read the standards, RFC 1034 and RFC 1035.
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"
let json = """
{
"Status": 0,
"TC": false,
"RD": true,
"RA": true,
"AD": false,
"CD": false,
"Question": [{
"name": "google.com.",
"type": 1
}],
"Answer": [{
"name": "google.com.",
"type": 1,
"TTL": 600,
"data": "142.251.163.102"
},
{
"name": "google.com.",
"type": 1,
"TTL": 600,
"data": "142.251.163.139"
},
{
"name": "google.com.",
"type": 1,
"TTL": 600,
"data": "142.251.163.101"
}
]
}
"""
struct JSONDNSReply: Codable {
var status: Int
var tc: Bool
var rd: Bool
var ra: Bool
var ad: Bool
var cd: Bool
var questions: [Question]
var answers: [Answer]
// Fix the case on all the fields and the pluralisation on the question and
// answer fields.
enum CodingKeys: String, CodingKey {
case status = "Status"
case tc = "TC"
case rd = "RD"
case ra = "RA"
case ad = "AD"
case cd = "CD"
case questions = "Question"
case answers = "Answer"
}
struct Question: Codable {
var name: String
var type: Int
}
struct Answer: Codable {
var name: String
var type: Int
var ttl: Int
var data: String
// Fix the case on `TTL`
enum CodingKeys: String, CodingKey {
case name = "name"
case type = "type"
case ttl = "TTL"
case data = "data"
}
}
}
func test() throws {
let data = Data(json.utf8)
let reply = try JSONDecoder().decode(JSONDNSReply.self, from: data)
print(reply)
}