创建JSON数据并解析为swift

时间:2018-06-04 10:27:03

标签: java json swift web-services webserver

我在正确地从Web服务器解析我的JSON数据时遇到问题。我试图从我在互联网上找到的文件解析JSON数据,它工作正常,但后来我试图创建我的一个JSON数据,并尝试在swift中解析它。问题是,当我在浏览器中调用Adress时,我可以看到JSON数据,但是当我在Swift中尝试它时,它不起作用。我也尝试调试,看看我得到的是响应,并且课程数组是空的。

这是我的Java代码:

@GET
@Path("/course")
@Produces(MediaType.APPLICATION_JSON)
public List getCourse(){
    List courseList = new ArrayList();
    Course pCourse = new Course(0, "name", "ll", null);
    courseList.add(pCourse);

    return courseList;
}

来自Java的“课程”数据:

public int id;
public String name;
public String link;
public String imageUrl;

public Course() {
}

public Course(int id, String name, String link, String imageUrl) {
    this.id = id;
    this.name = name;
    this.link = link;
    this.imageUrl = imageUrl;
}

这是我的Swift代码:

URLSession.shared.dataTask(with: costumeUrl) { (data, response, err) in
    guard let data = data else{ return}
//            let dataString = String(data: data, encoding: .utf8)
//            print(dataString)
    do{
        let course = try JSONDecoder().decode([Course].self, from: data)
        print(course)
    }catch let jsonError{
        print(jsonError)
    }
    }.resume()
来自Swift的

“课程”数据:

struct Course: Decodable {
    let id: Int
    let name: String
    let link: String
    let imageUrl: String

    init(json: [String: Any]){
        id = json["id"] as? Int ?? -1
        name = json["name"] as? String ?? ""
        link = json["link"] as? String ?? ""
        imageUrl = json["imageUrl"] as? String ?? ""

    }
}

以下是我浏览器中的回复:

[{"id":0,"imageUrl":null,"link":"ll","name":"name"}]

如果您有任何疑问或需要任何其他信息,请询问。 谢谢。

2 个答案:

答案 0 :(得分:6)

试试这个“课程” - 模型:

护理:如果JSON-Response中的值可以为空,请使用decodeIfPresent

class Course: Decodable {
    let id: Int
    let name: String
    let link: String
    let imageUrl: String?

    private enum CourseCodingKeys: String, CodingKey {
        case id = "id"
        case name = "name"
        case link = "link"
        case imageUrl = "imageUrl"
    }

    required init(from decoder: Decoder) throws {
        let courseContainer = try decoder.container(keyedBy: CourseCodingKeys.self)
        self.id = try courseContainer.decode(Int.self, forKey: .id)
        self.name = try courseContainer.decode(String.self, forKey: .name)
        self.link = try courseContainer.decode(String.self, forKey: .link)
        self.imageUrl = try courseContainer.decodeIfPresent(String.self, forKey: .imageUrl)
    }
}

答案 1 :(得分:2)

您可以像这样修改课程模型:

struct Course: Decodable {

    let id: Int?
    let name: String?
    let link: String?
    let imageUrl: String?

    private enum CodingKeys: String, CodingKey {
        case id
        case name
        case link
        case imageUrl
    }
}