с Scanner
вам нужно проверить, есть ли следующая строка с hasNextLine()
, поэтому цикл становится
while(sc.hasNextLine()){
str=sc.nextLine();
//...
}
, это читатели, которые возвращают значение null на EOF
в этом фрагменте кода, это зависит от того, правильно ли форматируется вход
Вы можете использовать Decodable, если у вас есть Struct вместо Class для простого анализа. Вот пример в Alamofire 5.0
struct SearchedUsers: Decodable {
let id: Int
let username: String?
let fullName: String?
let profilePicture: URL?
let isPrivate: Bool
}
AF.request("http://url_endpoint/").responseData { response in
do {
// data we are getting from network request
let decoder = JSONDecoder()
let response = try decoder.decode([SearchedUsers].self, from: response.data!)
} catch { print(error) }
}
Если вы знаете, как разбирать словарь, то вы должны знать, как его создать;) Существуют инструменты для создания собственного класса модели, например: http://www.jsoncafe.com/ [114 ]
РЕДАКТИРОВАТЬ : Как предполагает Роберт в разделе комментариев ниже, вы можете выучить Decodable
.
Вы можете использовать это, чтобы дать себе представление о том, как может или должен выглядеть модельный класс. Используйте его так, как вам нравится. В приличном проекте может быть множество данных, и вы не хотите делать из него модель класса, особенно если вы единственный, кто обрабатывает проект iOS.
Итак, мы предполагаем, что у нас есть эти данные json, основанные на вашем посте:
{
"id": 1,
"username": "dd",
"fullName": "dd",
"profilePicture": "ddd",
"isPrivate": true
}
Мы могли бы сделать из него модель примерно так:
//
// UserRootClass.swift
// Model Generated using http://www.jsoncafe.com/
// Created on January 18, 2019
import Foundation
class UserRootClass : NSObject {
var fullName : String!
var id : Int!
var isPrivate : Bool!
var profilePicture : String!
var username : String!
/**
* Instantiate the instance using the passed dictionary values to set the properties values
*/
init(fromDictionary dictionary: [String:Any]){
fullName = dictionary["fullName"] as? String
id = dictionary["id"] as? Int
isPrivate = dictionary["isPrivate"] as? Bool
profilePicture = dictionary["profilePicture"] as? String
username = dictionary["username"] as? String
}
/**
* Returns all the available property values in the form of [String:Any] object where the key is the approperiate json key and the value is the value of the corresponding property
*/
func toDictionary() -> [String:Any]
{
var dictionary = [String:Any]()
if fullName != nil{
dictionary["fullName"] = fullName
}
if id != nil{
dictionary["id"] = id
}
if isPrivate != nil{
dictionary["isPrivate"] = isPrivate
}
if profilePicture != nil{
dictionary["profilePicture"] = profilePicture
}
if username != nil{
dictionary["username"] = username
}
return dictionary
}
}
Класс модели выше было сделано с помощью инструмента, который я дал выше, но я удалил методы протокола NSCoding
.
Надеюсь, это поможет! Удачи и добро пожаловать в Stackoverflow.