I did some changes to an specific part of a json, an array to be more specific, to finish I want to save the changes in the json, but I can't because xcode give me this error:
"Cannot assign value of type '[JSON]' to type 'JSON'"
This is a sample of the code:
let originalSessionJson = dataObject!.sessionJson
var json:[JSON] = originalSessionJson["activity"].arrayValue
for i in 0 ..< json.count{
.
.
.
}
dataObject?.sessionJson["activity"] = json
Thanks for the help.
Perhaps you mean this:
dataObject?.sessionJson["activity"].arrayObject = json
Related
First off, what do we call a dictionary with a format like this in iOS?
(
{
name = "Apple";
value = "fruit-1";
},
{
name = "Banana";
value = "fruit-2";
}
)
And for my main question. I somehow need to format a string of JSON, like this:
[{"name":"Apple","value":"fruit-1"},{"name":"Banana","value":"fruit-2"}]
into whatever that format is called (of the string above).
For context, the existing approach of my project uses CoreData where the Server response (which uses the mystery format above) gets saved locally as a String, and I want to follow that format.
EDIT: for more context, I really need to just get the first format into the database because a module of a project was built to read the data with that format (e.g. make use of NSString.propertyList()).
Using a library called ios hierarchy viewer, I can see the saved object in the device.
Original format, server json to db (core data) in Objective-C:
What I've been trying to do in Swift, server json to local using JSONSerialization:
First off, what do we call a dictionary with a format like this in iOS?
According to the documentation of NSString.propertyList(), that's a "text representation of a property list".
It's a wonky, non-standard pretty-printing obtained by calling NSArray.description or NSDictionary.description.
Here's an example that shows a round-trip of data:
// The opening `{` indentation is fucky, but that's how it's generated.
let inputPropertyList = """
(
{
name = "Apple";
value = "fruit-1";
},
{
name = "Banana";
value = "fruit-2";
}
)
"""
// The result is an `Any` because we don't know if the root structure
// of the property list is an array or a dictionary
let deserialized: Any = inputPropertyList.propertyList()
// If you want the description in the same format, you need to cast to
// Foundation.NSArray or Foundation.NSDictionary.
// Swift.Array and Swift.Dictionary have a different description format.
let nsDict = deserialized as! NSArray
let roundTrippedPropertyList = nsDict.description
print(roundTrippedPropertyList)
assert(roundTrippedPropertyList == inputPropertyList)
The second format you show is what you get when you display an object in the debug console. That's the output of the object's description property. It isn't a "JSON string", exactly.
If you want to convert your objets to a true JSON string, see below.
As Alexander pointed out, the first string in your question is the output from NSString's propertyList() function. The format looks quite similar to "pretty-printed" JSON, but it's different enough that it it won't work that way.
The `propertyList() function is a debugging-only function, and I don't know of an existing way to parse that back into objects. If that is the string that's being sent by your server, your server is broken. If that's what you see in core data when you log the contents of a field, it's probably a misunderstanding on your part.
To convert an object to pretty JSON, see this answer, where I created an extension to the Encodable format that implements a property "prettyJSON":
extension Encodable {
var prettyJSON: String {
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
guard let data = try? encoder.encode(self),
let output = String(data: data, encoding: .utf8)
else { return "Error converting \(self) to JSON string" }
return output
}
}
That should work for any object that supports the Encodable protocol. (And your object should.)
I have received the following string:
{"records":[{"id":"rec4haaOncoQniu8U","fields":{"orders1":5},"createdTime":"2020-02-08T09:08:22.000Z"}]}
I am not understanding how I can process and separate the values of the json in mql4 using the "JAson.mqh " library, located here: https://www.mql5.com/en/code/13663
I need the values of "orders" located under "fields" , value = 5.
the only "KEYS" that changes are the keys within the "fields" values.
i would like to be able to get the values with something like this:
string value1 = Result[0].["fields"].["orders1"]; //5
string value2 = Result[0].["fields"].["orders2"];
Please let me know what I can do.
You can get the value using the following format. Note that it has to be casted to a type. (I have casted it to int as it is the type it is in the JSON, but you can cast it to string as well)
int value1 = json["records"][0]["fields"]["orders1"].ToInt(); // if you want to make it a string use ToStr() instead of ToInt()
Here is a full example of what I did
string jsonString = "{\"records\": [{\"id\": \"rec4haaOncoQniu8U\",\"fields\": {\"orders1\": 5 }\"createdTime\": \"2020-02-08T09:08:22.000Z\"}]}";
if(json.Deserialize(jsonString))
Alert(json["records"][0]["fields"]["orders1"].ToInt());
Hope it helped.
I have a json.I am trying to parse that with that code.But its says
Could not cast value of type '__NSArrayM' to 'NSDictionary'
do {
let dataDictionary: NSDictionary = try NSJSONSerialization.JSONObjectWithData(responseObject as! NSData, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary // <------ Error
if let customerArray = dataDictionary.valueForKey("cart") as? NSArray {
for js in customerArray {
let nameArray = js.valueForKey("name")
let idArray = js.valueForKey("id")
}
}
}
Thank you for your helps
The root object in your data is an array, not a object (dictionary).
You need to dynamically decide how to handle your JSON depending on the deserialized object.
What it's telling you is that the JSON object that you're parsing is not a dictionary, it's an array. So if you change it so that you treat its value as an array instead of a dictionary, you'll be able to iterate over that.
You need to reevaluate your JSON to ensure that it's structured the way you think it is. It would also be useful if you posted the JSON that you're trying to parse so that we can see it's structure as well.
I want to save data including string, number, date and coordinate in a file, and then transmit the file to a server. How to do this using swift?
And I'd like to process these data from the server in the future. What type of file is better to save them?
If i am getting this right you can use NSData
First you have to create a dictionary like this
var dictionary = [String:AnyObject]()
dictionary["age"] = 13
dictionary["name"] = "Mike"
Then you have to transform this dictionary into NSData using nsjsonserialization
if let data = NSJSONSerialization.dataWithJSONObject(dictionary, options:NSJSONWritingOptions(0), error:nil) as NSData? {
request.HTTPBody = data
}
But this is always depend on what the server is able to understand
Hope i helped. Sorry for my english
I have a json object as below
{"level" :{"currentLevel":"1","score":"100"}}
I have this json data in my project folder and I am using SwiftyJSON to parse my son and read the values. Everything looks fine.
Now I need to update the score and I am trying as below
var json = JSON({"level" :{"currentLevel":"1","score":"100"}})
json["level"]["score"] = "200"
This works fine too and the json is updated but below try fails
var json = JSON({"level" :{"currentLevel":"1","score":"100"}})
var updatedScore:String = "200"
json["level"]["score"] = updatedScore
I get compile error
Type [Subscript] does not conform to Protocol 'StringLiteralConvertible'
Any suggestion on how to update a SwiftJSON JSON object with a variable would be helpful
Thank you
Update:My Solution
This is what I have done finally
var json = JSON({"level" :{"currentLevel":"1","score":"100"}})
var level = (json["level"] as JSON).dictionaryObject
let updatedScore = "200"
level!["currentLevel"] = updatedScore
json["level"] = JSON(level!)
And this works
Try the below if you are saving the json as dictionary
((json["level"]as nsdictionary)["score"] as NSString = updatedScore)