Convert JSON String to JSON Object in Swift 4

Convert Json string to Json object in Swift 4

The problem is that you thought your jsonString is a dictionary. It's not.

It's an array of dictionaries.
In raw json strings, arrays begin with [ and dictionaries begin with {.


I used your json string with below code :

let string = "[{\"form_id\":3465,\"canonical_name\":\"df_SAWERQ\",\"form_name\":\"Activity 4 with Images\",\"form_desc\":null}]"
let data = string.data(using: .utf8)!
do {
if let jsonArray = try JSONSerialization.jsonObject(with: data, options : .allowFragments) as? [Dictionary<String,Any>]
{
print(jsonArray) // use the json here
} else {
print("bad json")
}
} catch let error as NSError {
print(error)
}

and I am getting the output :

[["form_desc": <null>, "form_name": Activity 4 with Images, "canonical_name": df_SAWERQ, "form_id": 3465]]

How to convert JSON String to JSON Object in swift?

based on discussion

import Foundation

let firstName = "Joe"
let lastName = "Doe"
let middleName = "Mc."
let age = 100
let weight = 45

let jsonObject: [String: [String:Any]] = [
"user1": [
"first_name": firstName,
"middle_name": middleName,
"last_name": lastName,
"age": age,
"weight": weight
]
]
if let data = try? JSONSerialization.data(withJSONObject: jsonObject, options: .prettyPrinted),
let str = String(data: data, encoding: .utf8) {
print(str)
}

prints

{
"user1" : {
"age" : 100,
"middle_name" : "Mc.",
"last_name" : "Doe",
"weight" : 45,
"first_name" : "Joe"
}
}

Convert plain string to JSON and back in Swift

When de-serializing JSON which does not have an array or
dictionary as top-level object you can pass the
.allowFragments option:

let jsonString =  "\"3\""
let jsonData = jsonString.data(using: .utf8)!

let json = try! JSONSerialization.jsonObject(with: jsonData, options: .allowFragments)

if let str = json as? String {
print(str) // 3
}

However, there seems to be no way to serialize a plain string to JSON
with the JSONSerialization class from the Foundation library.

Note that according to the JSON specification,
a JSON object is a collection of name/value pairs (dictionary) or
an ordered list of values (array). A single string is not a valid
JSON object.

How to parse json in swift (convert json string to string)

You get a json string so you can try

  let jsonstring = "\"asdf\""
let data = jsonstring.data(using: .utf8)

do {
if let str = try JSONSerialization.jsonObject(with: data!, options:.allowFragments) as? String {
print(str)
}

}
catch let caught as NSError
{
}

Simple and clean way to convert JSON string to Object in Swift

Here are some tips how to begin with simple example.

Consider you have following JSON Array String (similar to yours) like:

 var list:Array<Business> = []

// left only 2 fields for demo
struct Business {
var id : Int = 0
var name = ""
}

var jsonStringAsArray = "[\n" +
"{\n" +
"\"id\":72,\n" +
"\"name\":\"Batata Cremosa\",\n" +
"},\n" +
"{\n" +
"\"id\":183,\n" +
"\"name\":\"Caldeirada de Peixes\",\n" +
"},\n" +
"{\n" +
"\"id\":76,\n" +
"\"name\":\"Batata com Cebola e Ervas\",\n" +
"},\n" +
"{\n" +
"\"id\":56,\n" +
"\"name\":\"Arroz de forma\",\n" +
"}]"

// convert String to NSData
var data: NSData = jsonStringAsArray.dataUsingEncoding(NSUTF8StringEncoding)!
var error: NSError?

// convert NSData to 'AnyObject'
let anyObj: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(0),
error: &error)
println("Error: \(error)")

// convert 'AnyObject' to Array<Business>
list = self.parseJson(anyObj!)

//===============

func parseJson(anyObj:AnyObject) -> Array<Business>{

var list:Array<Business> = []

if anyObj is Array<AnyObject> {

var b:Business = Business()

for json in anyObj as Array<AnyObject>{
b.name = (json["name"] as AnyObject? as? String) ?? "" // to get rid of null
b.id = (json["id"] as AnyObject? as? Int) ?? 0

list.append(b)
}// for

} // if

return list

}//func

[EDIT]

To get rid of null changed to:

b.name = (json["name"] as AnyObject? as? String) ?? ""
b.id = (json["id"] as AnyObject? as? Int) ?? 0

See also Reference of Coalescing Operator (aka ??)

Hope it will help you to sort things out,

change JSON to String in Swift

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
}


Related Topics



Leave a reply



Submit