How to convert Jackson TextNode to ArrayNode (jackson) - parsing

I have a string json where array is TextNode
{
"a" : "["b":12]"
}
How to convert this array as jackson ArrayNode instead of textNode

Related

Swift Printing an Array in a table form String and also adding special characters

Lets assume i have this string
var stringCSV = "Beth,Charles,Danielle,Adam,Eric\n17945,10091,10088,3907,10132\n2,12,13,48,11";
And i converted it into a 2D Array
[["Beth", "Charles", "Danielle", "Adam", "Eric"], ["17945", "10091", "10088", "3907", "10132"], ["2", "12", "13", "48", "11"]]
Below is the code i used to convert the String into a 2D Array and sort it.
struct Person {
let name: String
let id: String
let age: String
}
var csvFormatted = [[String]]()
stringCSV.enumerateLines { (line, _) in
var res = line.split(separator: ",",omittingEmptySubsequences: false).map{
String($0)
}
for i in 0 ..< res.count {
res[i] = res[i]
}
csvFormatted.append(res)
}
let properties = zip(csvFormatted[1],csvFormatted[2])
let namesAndProperties = zip(csvFormatted[0],properties)
let structArray = namesAndProperties.map { (name, properties) in
return Person(name: name, id: properties.0, age: properties.1)
}
let sortedArray = structArray.sorted {
return $0.name < $1.name
}
for i in sortedArray {
print(i.name, i.id, i.age)
}
i get the below output
Adam 3907 48
Beth 17945 2
Charles 10091 12
Danielle 10088 13
Eric 10132 11
But I wont to understand and know how i can print the sorted array back to string, just like it was before i splitted it into an array and sorted it and including the special characters like "\n" and ",".
and achieve something the below
Adam,Beth,Charles,Danielle,Eric\n
3907,17945,10091,10088,10132\n
48,2,12,13,11
Use map for each property and join it to create a comma separated row. Then using the results in an array join again with a new line character.
let csv = [array.map(\.name).joined(separator: ","),
array.map(\.id).joined(separator: ","),
array.map(\.age).joined(separator: ",")]
.joined(separator: "\n")

How to split uncode string into characters

I have strings like
"\U0aac\U0ab9\U0ac1\U0ab5\U0a9a\U0aa8",
"\U0a97\U0ac1\U0ab8\U0acd\U0ab8\U0acb",
"\U0aa6\U0abe\U0ab5\U0acb",
"\U0a96\U0a82\U0aa1"
But I want to split this strings by unicode character
I dont know hot to do. I know components seprated by function but it's no use here.
\nAny help would be apperiaciated
If the strings you're getting really contain \U characters, you need to parse them manually and extract the unicode scalar values. Something like this:
let strings = [
"\\U0aac\\U0ab9\\U0ac1\\U0ab5\\U0a9a\\U0aa8",
"\\U0a97\\U0ac1\\U0ab8\\U0acd\\U0ab8\\U0acb",
"\\U0aa6\\U0abe\\U0ab5\\U0acb",
"\\U0a96\\U0a82\\U0aa1"
]
for str in strings {
let chars = str.components(separatedBy: "\\U")
var string = ""
for ch in chars {
if let val = Int(ch, radix: 16), let uni = Unicode.Scalar(val) {
string.unicodeScalars.append(uni)
}
}
print(string)
}
You can map your array, split its elements at non hexa digit values, compact map them into UInt32 values, initializate unicode scalars with them and map the resulting elements of your array into a UnicodeScalarView and init a new string with it:
let arr = [
#"\U0aac\U0ab9\U0ac1\U0ab5\U0a9a\U0aa8"#,
#"\U0a97\U0ac1\U0ab8\U0acd\U0ab8\U0acb"#,
#"\U0aa6\U0abe\U0ab5\U0acb"#,
#"\U0a96\U0a82\U0aa1"#]
let strings = arr.map {
$0.split { !$0.isHexDigit }
.compactMap { UInt32($0, radix: 16) }
.compactMap(Unicode.Scalar.init)
}.map { String(String.UnicodeScalarView($0)) }
print(strings)
This will print
["બહુવચન", "ગુસ્સો", "દાવો", "ખંડ"]
So, the string that comes back already has the "\" because in order to use components you'd need to have an additional escaping "\" so that you'd be able to do:
var listofCodes = ["\\U0aac\\U0ab9\\U0ac1\\U0ab5\\U0a9a\\U0aa8", "\\U0aac\\U0ab9\\U0ac1\\U0ab5\\U0a9a\\U0aa8"]
var unicodeArray :[String] = []
listofCodes.forEach { string in
unicodeArray
.append(contentsOf: string.components(separatedBy: "\\"))
unicodeArray.removeAll(where: {value in value == ""})
}
print(unicodeArray)
I will revise this answer once you specify how you are obtaining these strings, as is I get a non-valid string error from the start.

How to search from array of SwiftyJSON objects?

I have an SwiftyJSON object.
How to search by key(name) from the array of SwiftyJSON object.
For Example :
let arrCountry = [JSON]()
Now one country array contains
{
countryid : "1"
name : "New York"
},
{
countryid : "2"
name : "Sydeny"
}
How to search by predicate or something?
If I search "y" from the array then it should return both object (Because both contains "y") in another JSON array. And If I type "Syd" then it should return only one object in JSON array. As LIKE query in SQL. And as we are doing with predicates...
Get the array from the JSON object with arrayObject, cast it to the proper type and apply the filter function, in this example to find the item whose name is def
if let array = arrCountry.arrayObject as? [[String:String]],
foundItem = array.first(where: { $0["name"] == "def"}) {
print(foundItem)
}
Edit: For a refined search with NSPredicate and a JSON result use this
let searchText = "y"
let searchPredicate = NSPredicate(format: "name contains[cd] %#", searchText)
if let array = arrCountry.arrayObject as? [[String:String]] {
let foundItems = JSON(array.filter{ searchPredicate.evaluateWithObject($0) })
print(foundItems)
}
You need to extract the dictionary Array from the JSON Object and the you can apply the Predicate to that array.

How to convert array object to JSON string . IOS 8 . Swift 1.2

I got an array of object like this
var AuditActivityDayListJson = Array<AuditActivityDayModel>()
class AuditActivityDayModel : Serializable {
var DayNumber : Int
var DayType : Int
var DayDateDisplay : String
var DayDate : String
override init() {
DayNumber = 0
DayType = 0
DayDateDisplay = ""
DayDate = ""
}
}
How can i convert it into json string like this
[{"DayType":1,"DayNumber":1,"DayDate":"2015-06-30", "DayDateDisplay":""},{"DayType":1,"DayNumber":2,"DayDate":"2015-07-01","DayDateDisplay":""}]
Thanks all for your answer . Please help.
If you want to use builtin functions like NSJSONSerialization (
https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSJSONSerialization_Class/ )
you basically need to convert all your objects to arrays, dictionaries, strings and numbers
In your case this should work, converting your objects to dictionaries before converting to a JSON string:
let jsonCompatibleArray = AuditActivityDayListJson.map { model in
return [
"DayNumber":model.DayNumber,
"DayType":model.DayType,
"DayDateDisplay":model.DayDateDisplay,
"DayDate":model.DayDate
]
}
let data = NSJSONSerialization.dataWithJSONObject(jsonCompatibleArray, options: nil, error: nil)
let jsonString = NSString(data: data!, encoding: NSUTF8StringEncoding)
For more complex scenarios I recommend SwiftyJSON ( https://github.com/SwiftyJSON/SwiftyJSON ) which makes error handling and more much easier.

How do I split a string into an array of characters with Swift? [duplicate]

How can I convert a String "Hello" to an Array ["H","e","l","l","o"] in Swift?
In Objective-C I have used this:
NSMutableArray *characters = [[NSMutableArray alloc] initWithCapacity:[myString length]];
for (int i=0; i < [myString length]; i++) {
NSString *ichar = [NSString stringWithFormat:#"%c", [myString characterAtIndex:i]];
[characters addObject:ichar];
}
It is even easier in Swift:
let string : String = "Hello 🐶🐮 🇩🇪"
let characters = Array(string)
println(characters)
// [H, e, l, l, o, , 🐶, 🐮, , 🇩🇪]
This uses the facts that
an Array can be created from a SequenceType, and
String conforms to the SequenceType protocol, and its sequence generator
enumerates the characters.
And since Swift strings have full support for Unicode, this works even with characters
outside of the "Basic Multilingual Plane" (such as 🐶) and with extended grapheme
clusters (such as 🇩🇪, which is actually composed of two Unicode scalars).
Update: As of Swift 2, String does no longer conform to
SequenceType, but the characters property provides a sequence of the
Unicode characters:
let string = "Hello 🐶🐮 🇩🇪"
let characters = Array(string.characters)
print(characters)
This works in Swift 3 as well.
Update: As of Swift 4, String is (again) a collection of its
Characters:
let string = "Hello 🐶🐮 🇩🇪"
let characters = Array(string)
print(characters)
// ["H", "e", "l", "l", "o", " ", "🐶", "🐮", " ", "🇩🇪"]
Edit (Swift 4)
In Swift 4, you don't have to use characters to use map(). Just do map() on String.
let letters = "ABC".map { String($0) }
print(letters) // ["A", "B", "C"]
print(type(of: letters)) // Array<String>
Or if you'd prefer shorter: "ABC".map(String.init) (2-bytes 😀)
Edit (Swift 2 & Swift 3)
In Swift 2 and Swift 3, You can use map() function to characters property.
let letters = "ABC".characters.map { String($0) }
print(letters) // ["A", "B", "C"]
Original (Swift 1.x)
Accepted answer doesn't seem to be the best, because sequence-converted String is not a String sequence, but Character:
$ swift
Welcome to Swift! Type :help for assistance.
1> Array("ABC")
$R0: [Character] = 3 values {
[0] = "A"
[1] = "B"
[2] = "C"
}
This below works for me:
let str = "ABC"
let arr = map(str) { s -> String in String(s) }
Reference for a global function map() is here: http://swifter.natecook.com/func/map/
There is also this useful function on String: components(separatedBy: String)
let string = "1;2;3"
let array = string.components(separatedBy: ";")
print(array) // returns ["1", "2", "3"]
Works well to deal with strings separated by a character like ";" or even "\n"
For Swift version 5.3 its easy as:
let string = "Hello world"
let characters = Array(string)
print(characters)
// ["H", "e", "l", "l", "o", " ", "w", "o", "r", "l", "d"]
Updated for Swift 4
Here are 3 ways.
//array of Characters
let charArr1 = [Character](myString)
//array of String.element
let charArr2 = Array(myString)
for char in myString {
//char is of type Character
}
In some cases, what people really want is a way to convert a string into an array of little strings with 1 character length each. Here is a super efficient way to do that:
//array of String
var strArr = myString.map { String($0)}
Swift 3
Here are 3 ways.
let charArr1 = [Character](myString.characters)
let charArr2 = Array(myString.characters)
for char in myString.characters {
//char is of type Character
}
In some cases, what people really want is a way to convert a string into an array of little strings with 1 character length each. Here is a super efficient way to do that:
var strArr = myString.characters.map { String($0)}
Or you can add an extension to String.
extension String {
func letterize() -> [Character] {
return Array(self.characters)
}
}
Then you can call it like this:
let charArr = "Cat".letterize()
An easy way to do this is to map the variable and return each Character as a String:
let someText = "hello"
let array = someText.map({ String($0) }) // [String]
The output should be ["h", "e", "l", "l", "o"].
for the function on String: components(separatedBy: String)
in Swift 5.1
have change to:
string.split(separator: "/")
Martin R answer is the best approach, and as he said, because String conforms the SquenceType protocol, you can also enumerate a string, getting each character on each iteration.
let characters = "Hello"
var charactersArray: [Character] = []
for (index, character) in enumerate(characters) {
//do something with the character at index
charactersArray.append(character)
}
println(charactersArray)
let string = "hell0"
let ar = Array(string.characters)
print(ar)
In Swift 4, as String is a collection of Character, you need to use map
let array1 = Array("hello") // Array<Character>
let array2 = Array("hello").map({ "\($0)" }) // Array<String>
let array3 = "hello".map(String.init) // Array<String>
You can also create an extension:
var strArray = "Hello, playground".Letterize()
extension String {
func Letterize() -> [String] {
return map(self) { String($0) }
}
}
func letterize() -> [Character] {
return Array(self.characters)
}
Suppose you have four text fields otpOneTxt, otpTwoTxt, otpThreeTxt, otpFourTxt and a string getOtp.
let getup = "5642"
let array = self.getOtp.map({ String($0) })
otpOneTxt.text = array[0] //5
otpTwoTxt.text = array[1] //6
otpThreeTxt.text = array[2] //4
otpFourTxt.text = array[3] //2
let str = "cdcd"
let characterArr = str.reduce(into: [Character]()) { result, letter in
result.append(letter)
}
print(characterArr)
//["c", "d", "c", "d"]

Resources