I'm trying to read a JSON file that I've created using the NewtonSoft JSON.Net parser in another (Windows) program. The JSON was created by the JSON.Net component when it serialized an array of objects. The sample JSON looks like the following (for this example I'm just showing two of the objects):
[{"MaxLength":23,"HasSpecialChars":false,"HasUpperCase":true,"Key":"firstOne"},
{"MaxLength":0,"HasSpecialChars":false,"HasUpperCase":false,"Key":"secondOne"}]
Notice that this is an array of objects in json.
Now I need some Swift code that will read this JSON in and write it out after values are altered in the program.
What I've Tried
I found this SO entry : Reading in a JSON File Using Swift However, to get an array of objects, that entry uses separate structs that are Codable like the following:
struct ResponseData: Decodable {
var thisNameShowsUpInJson: [SiteKey]
}
That forces the outer array to have it's own name property in the json.
For example, the only way the code at that post works is if my JSON is altered to include an outer object with a name (SiteKey) like the following:
{"thisNameShowsUpInJson": [{"MaxLength":23,"HasSpecialChars":false,"HasUpperCase":true,"Key":"firstOne"},
{"MaxLength":0,"HasSpecialChars":false,"HasUpperCase":false,"Key":"secondOne"}]
}
However, that is not correct for the way that JSON.Net writes an array of objects to a file.
Here's my simple Swift class that I want to serialize and deserialize:
class SiteKey : Codable{
var Key : String
var MaxLength : Int
var HasSpecialChars : Bool
var HasUpperCase : Bool
init(key : String, maxLength : Int,
hasSpecialChars : Bool,
hasUpperCase : Bool){
Key = key;
MaxLength = maxLength;
HasSpecialChars = hasSpecialChars;
HasUpperCase = hasUpperCase;
}
}
I'd like to read the data from a named file and deserialize the data into objects. Then, I'd like to serialize the in memory objects back out to a file like my example.