在Swift中,你可以使用JSONSerialization
类将JSON字符串转换为字典。要将 Swift 字典转换为 JSON 字符串,我们可以使用JSONSerialization类的data(withJSONObject:options:)方法。这个方法将字典转换为二进制数据,然后我们可以使用String(data:encoding:)方法将其转换为字符串形式。
JSON字符串转换为字典
以下是一个例子:
// jsonStr 转为Dict
func jsonToDict() {
print("json转为Dict")
// 假设你有一个JSON字符串
let jsonString = """
{
"name": "John Doe",
"age": 30,
"isDeveloper": true
}
"""
let jsonData = jsonString.data(using: .utf8)
let dictData = try? JSONSerialization.jsonObject(with: jsonData!, options: []) as? [String: Any]
print("dict data keys is:\(dictData?.keys)")
print("dict data values is:\(dictData?.values)")
}
JSON字符串转换为数组
示例代码:
// jsonStr 转为Array
func jsonToArray() {
print("jsonString转为数组")
let jsonStr = """
[
1,
2,
3,
4,
5
]
"""
let jsonData = jsonStr.data(using: .utf8)
let arrayData = try? JSONSerialization.jsonObject(with: jsonData!, options: []) as? [Int]
print("arrayData value is:\(arrayData)")
}
字典转为Json字符串
示例代码:
// Dict转为JsonStr
func dictToJson() {
print("dict转为Json字符串")
// 将字典转为JSON字符串
let dictData = ["name": "王思聪", "city": "New York", "age": 18] as [String: Any]
guard let jsonData = try? JSONSerialization.data(withJSONObject: dictData, options: []) else { return }
let jsonString = String(data: jsonData, encoding: .utf8)
print("dict转为jsonString:\(jsonString)")
}
数组转为Json字符串
示例代码:
// array转为jsonStr
func arrayToJson() {
print("array转为Json字符串")
let arrayData = ["name", "王思聪", "city", "New York", "age"]
guard let jsonData = try? JSONSerialization.data(withJSONObject: arrayData, options: []) else { return }
let jsonString = String(data: jsonData, encoding: .utf8)
print("array转为jsonString:\(jsonString)")
}
全部的代码和效果如下:
import SwiftUI
func getFood() -> String {
return ["🍏", "🍎", "🍐", "🍊", "🍌", "🍋", "🍉", "🍇", "🍓", "🫐"].randomElement()!
}
// json 反序列化
func jsonDecode() {
print("json 数据解码")
struct Person: Codable {
let name: String
let age: Int
let email: String
}
let jsonStr = """
{
"name": "John",
"age": 30,
"email": "john@example.com"
}
"""
// 将json字符串转换为Data
let jsonData = jsonStr.data(using: .utf8)
// JSONDecoder
let decoder = JSONDecoder()
// 使用decoder将Data转为结构体
let per1 = try! decoder.decode(Person.self, from: jsonData!)
print("person name: \(per1.name)")
print("person age: \(per1.age)")
print("persn email: \(per1.email)")
}
// json 序列化
func jsonToStr() {
print("json 转为字符串")
struct Person: Codable {
let name: String
let age: Int
let email: String
}
// 创建结构体实例
let per2 = Person(name: "EmployA", age: 18, email: "john@example.com")
// 创建jsonEncoder
let jsonEncoder = JSONEncoder()
// 将结构体实例per2转为Data
let jsonData = try? jsonEncoder.encode(per2)
print("jsonData: \(String(describing: jsonData))")
// 将data转为String
let jsonString = String(data: jsonData!, encoding: .utf8)!
print("jsonString: \(jsonString)")
}
// jsonStr 转为Dict
func jsonToDict() {
print("json转为Dict")
// 假设你有一个JSON字符串
let jsonString = """
{
"name": "John Doe",
"age": 30,
"isDeveloper": true
}
"""
let jsonData = jsonString.data(using: .utf8)
let dictData = try? JSONSerialization.jsonObject(with: jsonData!, options: []) as? [String: Any]
print("dict data keys is:\(dictData?.keys)")
print("dict data values is:\(dictData?.values)")
}
// jsonStr 转为Array
func jsonToArray() {
print("jsonString转为数组")
let jsonStr = """
[
1,
2,
3,
4,
5
]
"""
let jsonData = jsonStr.data(using: .utf8)
let arrayData = try? JSONSerialization.jsonObject(with: jsonData!, options: []) as? [Int]
print("arrayData value is:\(arrayData)")
}
// Dict转为JsonStr
func dictToJson() {
print("dict转为Json字符串")
// 将字典转为JSON字符串
let dictData = ["name": "王思聪", "city": "New York", "age": 18] as [String: Any]
guard let jsonData = try? JSONSerialization.data(withJSONObject: dictData, options: []) else { return }
let jsonString = String(data: jsonData, encoding: .utf8)
print("dict转为jsonString:\(jsonString)")
}
// array转为jsonStr
func arrayToJson() {
print("array转为Json字符串")
let arrayData = ["name", "王思聪", "city", "New York", "age"]
guard let jsonData = try? JSONSerialization.data(withJSONObject: arrayData, options: []) else { return }
let jsonString = String(data: jsonData, encoding: .utf8)
print("array转为jsonString:\(jsonString)")
}
struct ContentView: View {
@State var food = "🍏"
var body: some View {
VStack {
Spacer()
Spacer()
Spacer()
Text(food).font(.system(size: 80))
Button(action: {
food = getFood()
}, label: {
Text("今天吃啥?")
.padding()
.foregroundColor(.white)
.font(/*@START_MENU_TOKEN@*/ .title/*@END_MENU_TOKEN@*/)
}).background(.orange)
.cornerRadius(10)
Button(action: {
print("解码json")
jsonDecode()
}, label: {
Text("解码JSON").font(/*@START_MENU_TOKEN@*/ .title/*@END_MENU_TOKEN@*/).foregroundColor(.white).padding()
}).background(.pink).cornerRadius(10)
Button(action: {
jsonToStr()
}, label: {
Text("编码JSON").font(/*@START_MENU_TOKEN@*/ .title/*@END_MENU_TOKEN@*/).foregroundColor(.white).padding()
}).background(.blue).cornerRadius(10)
Button(action: {
print("json转为dict类型")
jsonToDict()
}, label: {
Text("Json转Dict").foregroundColor(.white).padding(10).font(/*@START_MENU_TOKEN@*/ .title/*@END_MENU_TOKEN@*/)
}).background(.yellow).cornerRadius(10)
Button(action: {
print("json转为数组")
jsonToArray()
}, label: {
Text("Json转Array").font(/*@START_MENU_TOKEN@*/ .title/*@END_MENU_TOKEN@*/).padding(10).foregroundColor(.white)
}).background(.gray).cornerRadius(10)
Button(action: {
print("dict数据转为json")
dictToJson()
}, label: {
Text("Dict转为Json").foregroundColor(.white).padding(10).font(/*@START_MENU_TOKEN@*/ .title/*@END_MENU_TOKEN@*/)
}).background(.green).cornerRadius(10)
Button(action: {
print("字典转为数组")
arrayToJson()
}, label: {
Text("Dict转数组").font(/*@START_MENU_TOKEN@*/ .title/*@END_MENU_TOKEN@*/).foregroundColor(.white).padding(10)
}).background(.purple).cornerRadius(10)
Spacer()
Spacer()
Spacer()
}
}
}