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)
Related
Im stuck trying to model a JSON array which has no property name into my swift project with the goal of parsing the data and using it in my app. I know how to do this when there is a NAME for the array but I don't know how to make swift and this lackluster JSON understand each other. The path to the first "Company" in the JSON is "0.Company". The error I get is "Value of type 'WorkData' has no member '0'"
Im including pictures of my full project so it is easier to understand the structure of the code and what im trying to do. Please look at the picture for a clearer understanding I apologize if Im not explaining it well i'm new to programming.
import Foundation
class WorkData: Codable {
let WorkData: [WorkData]
let Company: String
let worklogDate: String
let issue: String
}
func parseData(jsonDataInput: Data) {
let decoder = JSONDecoder() // an object that decodes JSON data
do {
let decodedData = try decoder.decode(WorkData.self, from: jsonDataInput)
let Company = decodedData.0.Company
let worklogDate = decodedData.0.worklogDate
let issue = decodedData.0.issue
} catch {
print (error)
}
}
}
json
Trying to model JSON in Swift
Parsing JSON
You cannot start JSON with an array because JSON itself is an object {}
See example below:
{
"WorkData" : [
{"Company" : ""},
{"Company" : ""},
{"Company" : ""}
]
}
let decodedData = try decoder.decode(LocalizationsResponse.self, from: jsonDataInput)
decodedData will be an array
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
I have :-
var myArray:Array = array<JSON>
I want :-
var myJSON:JSON = myArray as? JSON
but i get a warning:-
Cast from 'Array' to unrelated type 'JSON' always fails
Can anyone help me how to convert an Array object to a JSON object?
A little more insight what i am trying to do:-
(This might not be needed to answer my above question but still...) Note:- I am using objectMapper for mapping swiftyJSONObjects.
var monthArray = Array<JSON>
var allEventsInDayArray:Array<JSON> = [] // an empty array
for (_,dayObj) in monthArray
{
guard let dayEventsArray = dayObj["events"].array else { break }
allEventsInDayArray.appendContentsOf(dayEventsArray)
}
print(allEventsInDayArray)
var allEventsJSON:JSON? = JSON(allEventsInDayArray)
var EventModelArray:Array<EventModel>? = Mapper<EventModel>().mapArray(allEventsJSON?.object.allValues)
If I understood your question and you want to create a SwiftyJSON object from an array you should do like this:
var myJSON:JSON = JSON(myArray)
The string to convert:
[{"description": "Hi","id":2,"img":"hi.png"},{"description": "pet","id":10,"img":"pet.png"},{"description": "Hello! :D","id":12,"img":"hello.png"}]
The code to convert the string:
var json = JSON(stringLiteral: stringJSON)
The string is converted to JSON and when I try to count how many blocks are inside this JSON (expected answer = 3), I get 0.
print(json.count)
Console Output: 0
What am I missing? Help is very appreciated.
Actually, there was a built-in function in SwifyJSON called parse
/**
Create a JSON from JSON string
- parameter string: Normal json string like '{"a":"b"}'
- returns: The created JSON
*/
public static func parse(string:String) -> JSON {
return string.dataUsingEncoding(NSUTF8StringEncoding)
.flatMap({JSON(data: $0)}) ?? JSON(NSNull())
}
Note that
var json = JSON.parse(stringJSON)
its now changed to
var json = JSON.init(parseJSON:stringJSON)
I fix it on this way.
I will use the variable "string" as the variable what contains the JSON.
1.
encode the sting with NSData like this
var encodedString : NSData = (string as NSString).dataUsingEncoding(NSUTF8StringEncoding)!
un-encode the string encoded (this may be sound a little bit weird hehehe):
var finalJSON = JSON(data: encodedString)
Then you can do whatever you like with this JSON.
Like get the number of sections in it (this was the real question) with
finalJSON.count or print(finalJSON[0]) or whatever you like to do.
There is a built-in parser in SwiftyJSON:
let json = JSON.init(parseJSON: responseString)
Don't forget to import SwiftyJSON!
I'm using as follows:
let yourString = NSMutableString()
let dataToConvert = yourString.data(using: String.Encoding.utf8.rawValue)
let json = JSON(data: dataToConvert!)
print("\nYour string: " + String(describing: json))
Swift4
let json = string.data(using: String.Encoding.utf8).flatMap({try? JSON(data: $0)}) ?? JSON(NSNull())
I am trying to read the value from an XML element but I always get "Sequence contains to elements" error.
I already done my research but nothing works for my problem.
I want to read the Ack and Timestamp element values in this XML
<DoDirectPaymentResponse xmlns="urn:ebay:api:PayPalAPI">
<Timestamp xmlns="urn:ebay:apis:eBLBaseComponents">2014-09-16T04:41:56Z</Timestamp>
<Ack xmlns="urn:ebay:apis:eBLBaseComponents">Success</Ack>
</DoDirectPaymentResponse>
Here's my code for reading the Ack and Timestamp values
String xmlString = #xml;
using (XmlReader reader = XmlReader.Create(new StringReader(xmlString)))
{
XDocument xdoc = XDocument.Load(reader);
var timestamp = xdoc.Descendants("Timestamp").Single();
receipt.Timestamp = timestamp.Value;
var response = xdoc.Descendants("Ack").Single();
receipt.Response = response.Value;
}
Please help me with this. Thanks a lot.
You need to use proper XNamespace to access elements in the namespace :
XDocument xdoc = XDocument.Parse(xmlString);
XNamespace ns = "urn:ebay:apis:eBLBaseComponents";
var timestamp = xdoc.Descendants(ns+"Timestamp").Single();
receipt.Timestamp = timestamp.Value;
var response = xdoc.Descendants(ns+"Ack").Single();
receipt.Response = response.Value;
Side note: you can use XDocument.Parse() to load XML from XML string content.