Java 创建JSON数据并解析到swift
我在正确解析Web服务器中的JSON数据时遇到问题。我试图从我在互联网上找到的文件中解析JSON数据,效果很好,但随后我尝试创建我的一个JSON数据,并尝试用swift解析它。问题是,当我在浏览器中调用地址时,我可以看到JSON数据,但当我在Swift中尝试时,它不起作用。我还尝试调试以查看作为响应得到的结果,并且课程数组为空 以下是我的Java代码:Java 创建JSON数据并解析到swift,java,json,swift,web-services,webserver,Java,Json,Swift,Web Services,Webserver,我在正确解析Web服务器中的JSON数据时遇到问题。我试图从我在互联网上找到的文件中解析JSON数据,效果很好,但随后我尝试创建我的一个JSON数据,并尝试用swift解析它。问题是,当我在浏览器中调用地址时,我可以看到JSON数据,但当我在Swift中尝试时,它不起作用。我还尝试调试以查看作为响应得到的结果,并且课程数组为空 以下是我的Java代码: @GET @Path("/course") @Produces(MediaType.APPLICATION_JSON) public List
@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"}]
如果您有任何问题或需要任何其他信息,请询问。
谢谢。试试这个“课程”-模式:
注意:如果JSON响应中的值可以为空,请使用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)
}
}
您可以这样修改您的课程模型:
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
}
}
你能提供你的“课程”模型吗?@Teetz补充道,“课程”模型也很好。