[英]how to write correct JSON string file in swift
我创建了一个JSON字符串文件,其中包含
{
[{"teamName":"Arsenal",
"image":"Arsenal",
"nextMatch":"in 2 days",
"matches":[{"oppositeTeam":"teamName",
"matchTimings":"121212",
"matchId":"ID 213432"},
{"oppositeTeam":"teamName",
"matchTimings":"121212",
"matchId":"ID 213432"}],
"fixtures": {"oppositeTeam":"teamName",
"oppositeTeamScore":"7",
"homeTeamScore":"4",
"homeTeamCards":"True",
"oppositeTeamCards":"false",
"fixtureId":"ID 213432”}
}},
{"teamName":"Chelsea",
"image":"Chelsea",
"nextMatch":"in 2 days",
"matches":{"oppositeTeam":"teamName",
"matchTimings":"121212",
"matchId":"ID 213432"},
"fixtures": {"oppositeTeam":"teamName",
"oppositeTeamScore":"7",
"homeTeamScore":"4",
"homeTeamCards":"True",
"oppositeTeamCards":"false",
"fixtureId":"ID 213432”}
}},{
"teamName":"India",
"image":"India",
"nextMatch":"in 2 days",
}
] }
但是当我在在线Json Reader上检查此JSON时,它显示了很多错误,我是JSON解析的新手,不知道如何更正JSON
正确的JSON语法:
{
"teams":[
{
"teamName":"Arsenal",
"image":"Arsenal",
"nextMatch":"in 2 days",
"matches":[
{
"oppositeTeam":"teamName",
"matchTimings":"121212",
"matchId":"ID 213432"
},
{
"oppositeTeam":"teamName",
"matchTimings":"121212",
"matchId":"ID 213432"
}
],
"fixtures":{
"oppositeTeam":"teamName",
"oppositeTeamScore":"7",
"homeTeamScore":"4",
"homeTeamCards":"True",
"oppositeTeamCards":"false",
"fixtureId":"ID 213432"
}
},
{
"teamName":"Chelsea",
"image":"Chelsea",
"nextMatch":"in 2 days",
"matches":{
"oppositeTeam":"teamName",
"matchTimings":"121212",
"matchId":"ID 213432"
},
"fixtures":{
"oppositeTeam":"teamName",
"oppositeTeamScore":"7",
"homeTeamScore":"4",
"homeTeamCards":"True",
"oppositeTeamCards":"false",
"fixtureId":"ID 213432"
}
},
{
"teamName":"India",
"image":"India",
"nextMatch":"in 2 days"
}
]
}
您的错误没有整个数组的键,请在matchIds的结尾处使用印刷术引号和多余的右花括号。
我想学习,以便将来自己能做
好吧,要写出有效的JSON
100%而没有任何大问题,我建议Codable
,
现在,对于任何手动或本地编写的JSON
,我将
1-创建一个结构以确认Codable
。
2-创建该Object
的实例。
3-对该对象进行Encode
,然后将其转换为String
,它将100%确认为JSON
验证程序。
观察下面的代码。
struct MyOject: Codable {
var param1: String
var param2: Int
var param3: String
}
let myObj = MyOject(param1: "foo", param2: 1, param3: "bee")
let encodedData = try! JSONEncoder().encode(myObj) // encode the object as JSON Data
let myJSON = String(data:encodedData, encoding: .utf8)! // converting to String that is indeed JSON formatted
print(myJSON)
//Now to use it as object again we just need to Decode it. (the data)
let myObjResult = try! JSONDecoder().decode(MyOject.self, from: encodedData) // converted back as object
print(myObj.param1) // test reuslt should be (foo)
现在有什么好处
1-最重要的事情是可重用性,您可以根据需要进行多次重用。
2-100%有效的JSON
提供程序。
3-为您提供将来处理任何API Responses
技能。
4-到目前为止,这是最简单,最快的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.