Creating json in swift
879 просмотра
2 ответа
I want to createa json like this in swift:
{
"test1": 0,
"test2": 1435659978,
"test3": 1430479596
}
How can I create this json?
Автор: Tolgay Toklar Источник Размещён: 12.11.2019 10:01Ответы (2)
4 плюса
Решение
Create your object, in this case a Dictionary:
let dic = ["test1":0, "test2":1435659978, "test3":1430479596]
Create the JSON data from the object:
do {
let dic = ["test1":0, "test2":1435659978, "test3":1430479596]
let jsonData = try NSJSONSerialization.dataWithJSONObject(dic, options: NSJSONWritingOptions.PrettyPrinted)
} catch let error as NSError {
print(error)
}
Use the JSON data as a String if you need it:
do {
let dic = ["test1":0, "test2":1435659978, "test3":1430479596]
let jsonData = try NSJSONSerialization.dataWithJSONObject(dic, options: NSJSONWritingOptions.PrettyPrinted)
let str = String(data: jsonData, encoding: NSUTF8StringEncoding)
} catch let error as NSError {
print(error)
}
Автор: ayaio
Размещён: 07.07.2015 08:21
3 плюса
Check out this github page instead
I created a small class that can take any Swift class object and turn it into JSON. Can handle composition.
import Foundation
class JSONSerializer {
static func toJson(object: Any) -> String {
var json = "{"
let mirror = Mirror(reflecting: object)
let mirrorChildrenCollection = AnyRandomAccessCollection(mirror.children)!
let size = mirror.children.count
var index = 0
for (optionalPropertyName, value) in mirrorChildrenCollection {
let propertyName = optionalPropertyName!
let property = Mirror(reflecting: value)
var handledValue = String()
if value is Int || value is Double || value is Float || value is Bool {
handledValue = String(value ?? "null")
}
else if let array = value as? [Int?] {
handledValue += "["
for (index, value) in array.enumerate() {
handledValue += value != nil ? String(value!) : "null"
handledValue += (index < array.count-1 ? ", " : "")
}
handledValue += "]"
}
else if let array = value as? [Double?] {
handledValue += "["
for (index, value) in array.enumerate() {
handledValue += value != nil ? String(value!) : "null"
handledValue += (index < array.count-1 ? ", " : "")
}
handledValue += "]"
}
else if let array = value as? [Float?] {
handledValue += "["
for (index, value) in array.enumerate() {
handledValue += value != nil ? String(value!) : "null"
handledValue += (index < array.count-1 ? ", " : "")
}
handledValue += "]"
}
else if let array = value as? [Bool?] {
handledValue += "["
for (index, value) in array.enumerate() {
handledValue += value != nil ? String(value!) : "null"
handledValue += (index < array.count-1 ? ", " : "")
}
handledValue += "]"
}
else if let array = value as? [String?] {
handledValue += "["
for (index, value) in array.enumerate() {
handledValue += value != nil ? "\"\(value!)\"" : "null"
handledValue += (index < array.count-1 ? ", " : "")
}
handledValue += "]"
}
else if let array = value as? [String] {
handledValue += "["
for (index, value) in array.enumerate() {
handledValue += "\"\(value)\""
handledValue += (index < array.count-1 ? ", " : "")
}
handledValue += "]"
}
else if let array = value as? NSArray {
handledValue += "["
for (index, value) in array.enumerate() {
handledValue += "\(value)"
handledValue += (index < array.count-1 ? ", " : "")
}
handledValue += "]"
}
else if property.children.count > 0 {
handledValue = toJson(value)
}
else {
handledValue = String(value) != "nil" ? "\"\(value)\"" : "null"
}
json += "\"\(propertyName)\": \(handledValue)" + (index < size-1 ? ", " : "")
++index
}
json += "}"
return json
}
}
//Test nonsense data
class Nutrient {
var name = "VitaminD"
var amountUg = 4.2
var intArray = [1, 5, 9]
var stringArray = ["nutrients", "are", "important"]
}
class Fruit {
var name: String = "Apple"
var color: String? = nil
var weight: Double = 2.1
var diameter: Float = 4.3
var radius: Double? = nil
var isDelicious: Bool = true
var isRound: Bool? = nil
var nullString: String? = nil
var date = NSDate()
var optionalIntArray: [Int?] = [1, 5, 3, 4, nil, 6]
var doubleArray: [Double?] = [nil, 2.2, 3.3, 4.4]
var stringArray: [String] = ["one", "two", "three", "four"]
var optionalArray: [Int] = [2, 4, 1]
var optionalStringArray: [String?] = ["topdoge", nil, "hejsan"]
var nutrient: Nutrient = Nutrient()
var nutrientNull: Nutrient? = Nutrient()
var nutrientNullN: Nutrient? = nil
func eat() {
print("eating the fruit")
}
}
var fruit = Fruit()
var json = JSONSerializer.toJson(fruit)
print(json)
Paste it into a playground to try. It's Swift 2.0 and requires XCode beta.
https://gist.github.com/peheje/cc3618253d4f38ea4885
Автор: Peheje Размещён: 08.07.2015 09:23Вопросы из категории :
- swift Как я могу программным образом определить, работает ли мое приложение в симуляторе iphone?
- swift iOS: Convert UTC NSDate to local Timezone
- swift Как установить цель и действие для UIBarButtonItem во время выполнения
- swift Жирный и не жирный текст в одном UILabel?
- swift Найти касательную точки на кубической кривой безье
- swift Как я могу рассчитать разницу между двумя датами?
- swift How to get text / String from nth line of UILabel?
- swift Можно ли программно прокрутить до нужной строки в UIPickerView?
- swift Отключение клавиатуры в UIScrollView
- swift Как контролировать межстрочный интервал в UILabel
- swift Формат UILabel с маркерами?
- swift Как я могу создавать локальные уведомления в iOS?
- swift UILabel с текстом двух разных цветов
- swift Многострочная метка iOS в Интерфейсном конструкторе
- swift Неизвестный пароль UITextField
- swift Delete all keys from a NSUserDefaults dictionary iOS
- swift Скопируйте CGContext в другой CGContext
- swift Как ждать в Objective-C и Swift
- swift Событие изменения текста UITextField
- swift Получить системный том iOS