Parse JSON string - ios sdk - json

{"aps":{
"alert":"New Test For The Win",
"sound":"default"
},
"fk_device":"1513"
}
I have this JSON NSString. How can I parse this JSON string and get fk_device value?

You can try this library JSONKit. To get the string, you can do something like this:
NSDictionary *deserializedData = [jsonString objectFromJSONString];
NSString *string = [deserializedData objectForKey:#"fk_device"];

Related

Convert String to Json in Ballerina

Is there a way to convert string to json in Ballerina ?
I found this PR - Add jsons:parse() method to get a JSON from a string where it says adding support to parse string to json, but couldn't find any example.
I tried the following:
string person = {"name":"John", "address":{"number":89, "street":"main street", "town": "Colombo"}};
json personJson = sons:parse(person);
But it gave me an error:
undefined package 'jsons'
undefined function 'parse'
The correct way to convert a string to json in ballerina is to use the readJson function from StringReader. What you have tried was an old approach which is no longer supported.
Following example shows how this could be done using the StringReader.
import ballerina/io;
public function main(string... args) {
string str = "{\"name\":\"John\", \"address\":{\"number\":89, \"street\":\"main street\", \"town\":\"Colombo\"}}";
io:StringReader sr = new(str, encoding = "UTF-8");
json j = check sr.readJson();
io:println(j);
}
More info about StringReader can be found from the docs at - https://ballerina.io/learn/api-docs/ballerina/io.html#StringReader
From Ballerina swan lake onward, you can use the fromJsonString() method to convert a string to json:
string jsonStr = "{\"key\": \"value\"}";
json|error converted = jsonStr.fromJsonString();
if (converted is error) {
io:println("Error in parsing json");
} else {
io:println(converted);
}

How to save SwiftyJson string array into string array

How can i save the SwiftyJSON String array into String of Array in swift
let jsonStr: JSON = JSON(socketDictionary.myStructValue)
print(jsonStr)
The output is:
["1CZ3isxgnmrY8w1eUJmCjNSm2fvhfXYkNQ","12ZKF9uZnaz5Wk6wVvmphE42LjM5M51upV","1LzPBqfrsdxDeFkeZqSGuaS3zxw8wTRQXx","1Z5qe2NSZyzvoNbmU7tuB7AaH7i4JQJXJ","15BKJq6Q2QHdw8v93JwBqy5GKrbLDWbbUR","1DCVJrzfZrFxqBGRF3H744SB1dC8aw5Rgn","1QGsCPM2HLfAMyFdfWddzijbzXF6cwm7RA","1QGW6T2KLTuWuu5qkfmZ8E63amtZmasRSu","1CLSGF92T8936tfm9qKG4N6cQir7AKSM7Q","1C7wnv7TBaX3H3xeHycr95h9mzzvVUq9Wz","1vBegRfLZbiwyEZ9LXo4d1KbLnUEyZLpF","1Nh9mxHuXF2T6V8qwHf95T6G24EFaQRG2M","16S2TgTX4ArtNW2htUCdCk6KvAZZFfw8Xi","1J3f1UoAGwmbK1aN9vTYex5rjpDnDewtTH","1BsawvNcAs289FZv3LbZY6STweTVJk6DeW","1LSQBT7QuBBSkwyFZpsxoEuw3oBDe57DT1","1LUSG4Pm7FiiCBUcEjWduLsCjswPheHZyF","1KPD18LDsmemHUR8TyLc8C3LJRKTgxVFe5","1FASJSpNjLVTEqmM72KjrZ85H7GudbQxZn","1MZxxP5YjLh29W7tgcrtYc2ywuAjdB2FC4","1JakuQCqpcmz1husavN8dHFGQyy3yDRCrD","177D2KQ4gd6kW1b4jTs9TLjUAV927F6Wc4","1PgKwdsKBqFNsZz4JcZ82kqBXRpCbWjPae","1P2iYhmVxhg3W8tEeQQK23NY5mKxHPbNnQ","14AgWBp6XYw12cBdAvdwz3sh9issWX7UnW","1DMPZjYf9LvHe3p7ZvZTVYsasGJps5QWWu","1MncjTfvdkNp1P1z22LAgbXU8mmTi59sLw","1PLLzt7Jiww6KqfsRwM6aW4z6pHoJNiDLR","1JvGhkZ26hy1Tjmxyx8C9amzo3pt6Ecxfh","1D3P1oYE9PBJhz9HYXeVJwuM5Qgg6RdYRu","1DGaE7K1nPjoVuL7BD4y3NWZvQ8gGNzenj","1h81XFB5nLsRJu2UtPinJx3niv1LMWSj5","18tAQ6awwcecSbxT63kQBmyJm7hWQLDppe","17p9vLfD1Q3Hdxp5zCNuX4cSe7TDjvzDXc","1GAsmp3j26Y6AkMG1jtVoZFBxZnJMSWQLF","1MJa3EFHFJwY2myibcVWiB6zuofFFaBWAR","19FwYXp1vfgU7bNojsggkuVZsiiAKRxbF7","18tG7Czk2akY2qbcn651CwCWzv9QA3DKUn","1AzacPufLFp7tL593Yimg7cnu4SymganbL","1EifaT43avdWcsXMhyVHvPmtNz7YyfDEnZ","17Xax4sY5Z694QQEKKz1ioaSrxXujnoa1y","18G4HWStJBVE4k4uLnif5cKAsyXpKx3VqY","1FUKc1zh8ia2h1j8Z1DqTTVQ2cJSyx7AnW","1HQq9mQxePKZg8eDncggx9LZ3ufc6sYSPp","14mKUH5jFmEW6DiKAiGJmeztqZ46XQkxch","1JWJwbiPzehXz8D5s7jTddEDxtMLBaFfkV","1GZbEdUjBhqZfp1JAyaoCZRTCiXSa4gbty","1D69wSHc1wK778gYWogzrm2hnerCBs1ZC6","12aa3sB1DTQDGT5UQHWnU71ziLLvQHKLTr","1AF2rxRKJbtUTNH4iyX5csrrG66Y723YwP","1AR77rXiZga2XUd2W7Wk1jZQfGjtK3gDBs","1PVJqkWLEed11uHHBeH3x4ya6zSjS7sv2e","168VzjYSz3tYaYLLoF28WKoc2NzBTAM866","13SnzBJL7jrHfPCWSAS8GD4ctmKAfgvTaa","16KBupqzu8hUCzqjdgr6ZFfM9TFnRkz82u","1Pd7NY5onBAQtwjf9aKGaun8QDhuoFf7jr","1LM65ijpT6SnTwQHd6bz44RZAaaVXEmT8x","1Mzg7bLFoA5wrDT2gUk7M9JPA7yxGYGN7c","1N7Tw2KDaUWRexGCoNSa5ecZkDHdvNRw1Z","1GPRVhFa1X99VqYJuRR6wBP1vz1txWiNYQ","1JaaeGaNeytwTPh9Dwv9XdcUyfzmhDVi6a"]
i want to save this json output array to simple array and then iterate those array
Just use dicionaryObject from SwiftyJSON. This will convert JSON value into [String: Any].
Ex.: jsonStr.dicionaryObject

change JSON to String in Swift [duplicate]

This question already has answers here:
Simple and clean way to convert JSON string to Object in Swift
(17 answers)
Closed 5 years ago.
I got JSON file from API but the content looks like this:
[
"https:\/\/seekingalpha.com\/article\/4125943-apple-homepod-delay-big-deal?source=feed_symbol_AAPL"
]
Suppose the JSON Object above is named as json. Then I just convert the object to string using String() method.
strings = String(json)
When I changed it to String type, it seems to get unnecessary '\n' and whitespace in it.
"[\n \"https:\\/\\/seekingalpha.com\\/article\\/4125943-apple-homepod-delay-big-deal?source=feed_symbol_AAPL\"\n]"
So it seems like the content of the JSON file is:
["\n""whitespace""whitespace""String""\n"]
When I changed it to String type, Swift just treats all the elements in it as a whole and wrapped it as a string.
My question is, how to extract the String inside so it looks like:
"https:\\/\\/seekingalpha.com\\/article\\/4125943-apple-homepod-delay-big-deal?source=feed_symbol_AAPL\"
As I am not so familiar with Swift so how to extract String or JSON Object is not easy for me. Any hints or help will be appreciated.
Swift 3,4 :
The given JSON format is Array of String.
if let json = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String]{
let firstElement = json?.first ?? "Element Not Found!"
print(firstElement)
}
Swift 4:
if let json = try? JSONDecoder().decode(Array<String>.self, from: data){
let firstElement = json.first ?? "First Element Not Found!"
print(firstElement)
}
Note:
If your the Array contains more than one String. Here,urls is the class variable. i.e.,var urls = [String]()
Swift 3,4 :
if let json = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String]{
if json != nil{
self.urls = json!
}
print(self.urls)
}
Swift 4:
if let json = try? JSONDecoder().decode(Array<String>.self, from: data){
self.urls = json
}
1. You will first have to convert JSON to Data
2. Convert data to string wrt to encoding
func jsonToString(jsonTOConvert: AnyObject){
do {
let data = try JSONSerialization.data(withJSONObject: jsonTOConvert, options: JSONSerialization.WritingOptions.prettyPrinted)
let convertedString = String(data: data, encoding: String.Encoding.utf8)
} catch let myJSONError {
print(myJSONError)
}
}
You are asking that a String be created with the contents:
[
"https:\/\/seekingalpha.com\/article\/4125943-apple-homepod-delay-big-deal?source=feed_symbol_AAPL"
]
The string object is doing exactly what you told it to — the thing you've asked it to represent begins with a square bracket, then there's a line break, then two spaces, etc, so the string contains a square bracket, then a line break, then two spaces, etc. There is no 'unnecessary' \n, there is only the \n you told it to put in.
If you obtained a JSON object then you need to parse it as JSON. JSONSerialization will do that job. What you've actually got is an array with a single item, which is a string. So JSONSerialization will return an array. The first item of that should be a string that is the seekingalpha.com URL.

Parse an entire JSON array into a table using 1 key

I need some help with parsing JSON in Swift.
[{"Database":"information_schema"}
{"Database":"Tonysnasa"},
{"Database":"camaleonsystems"},
{"Database":"camaleonsystems_back"},
{"Database":"camaleonsystemsfortest"}]
^ - Above is my JSON
v - Below is my Swift code.
let jsonDB: String! = jsonResult[0]["Database"] as NSString
println(jsonDB)
self.DBList.append(jsonDB)
I want to parse all of the "Database:" entries. When I try the method above, I am only able to parse information_schema.
How can I parse all the "Database:"'s into my table?
looks like it is an array of dictionaries,to get them all you should be able to use:
var jsonDB : [Dictionary<String, String>] = jsonResult
for currentDictionary in jsonDB{
var currentEntry = currentDictionary["Database"] as String
println(currentEntry)
self.DBList.append(currentEntry)
}

Receiving JSON in salesforce

I am trying to receive a JSON string in salesforce by converting a blob in the body of an Http request. However, when I convert the blob to a string there are \ characters that get inserted into the request which prevents me from parsing.
I then tried to take the string and remove all \ characters... that didn't work either.
RestRequest req = RestContext.request;
Blob jsonBlob = req.requestBody;
String jsonString = jsonBlob.toString();
return jsonString;
The original string (the one that is received as a blob) looks like this:
{"putTimeCard":{"timecard":{"timeCardID": "","employeeID": ""}}
And after converting to a salesforce string and assigned to the jsonString is altered to:
{\"putTimeCard\":{\"timecard\":{\"timeCardID\": \"\",\"employeeID\": \"\"}}
Has anyone found a solution for this?
Thanks
The JSON Deserializer can parse the string with the escape characters. You can either deserialize into an object like so:
String jsonString = '{\"putTimeCard\":{\"timecard\":{\"timeCardID\": \"\",\"employeeID\": \"\"}}}'
Timecard t = (Timecard) JSON.deserialize(jsonString, Type.forName('Timecard'));
or if you just want a map of objects you can do the following:
String jsonString = '{\"putTimeCard\":{\"timecard\":{\"timeCardID\": \"\",\"employeeID\": \"\"}}}'
Map<String, Object> m = (Map<String, Object>) JSON.deserializeUntyped(jsonString);