创建JSON数据并解析为swift

Der*_*ten 0 java webserver json web-services swift

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

这是我的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;
}
Run Code Online (Sandbox Code Playgroud)

来自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;
}
Run Code Online (Sandbox Code Playgroud)

这是我的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()
Run Code Online (Sandbox Code Playgroud)

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 ?? ""

    }
}
Run Code Online (Sandbox Code Playgroud)

这是我浏览器中的响应:

[{"id":0,"imageUrl":null,"link":"ll","name":"name"}]
Run Code Online (Sandbox Code Playgroud)

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

Tee*_*etz 6

试试这个"课程" - 模型:

注意:decodeIfPresent如果JSON-Response中的值可以为null,请使用此选项.

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)
    }
}
Run Code Online (Sandbox Code Playgroud)