How to Parse JSON in JSON with Swiftyjson

How to convert a string into JSON using SwiftyJSON

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)!

  1. 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.

Parse JSON response with SwiftyJSON

Try changing this line:

let body = JSON(string)

and call the init(parseJSON:) initializer of JSON that takes a String as parameter, like this:

let body = JSON(parseJSON: string)

How to parse JSON Array Objects with SwiftyJSON?

Actually it would be better to define a struct for object in Array.

public struct Item {

// MARK: Declaration for string constants to be used to decode and also serialize.
private struct SerializationKeys {
static let sno = "sno"
static let title = "title"
static let tableid = "tableid"
}

// MARK: Properties

public var sno: String?
public var title: String?
public var tableid: String?

// MARK: SwiftyJSON Initializers
/// Initiates the instance based on the object.
///
/// - parameter object: The object of either Dictionary or Array kind that was passed.
/// - returns: An initialized instance of the class.
public init(object: Any) {
self.init(json: JSON(object))
}

/// Initiates the instance based on the JSON that was passed.
///
/// - parameter json: JSON object from SwiftyJSON.
public init(json: JSON) {
sno = json[SerializationKeys.sno].string
title = json[SerializationKeys.title].string
tableid = json[SerializationKeys.tableid].string
}
}

And you need to map your array of JSON to Item objects.

var items = [Item]()
if let arrayJSON = json.array
items = arrayJSON.map({return Item(json: $0)})
}

How to parse JSON dictionary using SwiftyJSON and Alamofire

Change your response code like below

switch response.result {
case .success(let value):
let response = JSON(value)
print("Response JSON: \(response)")

let newUser = User(json: response)
self.userData.append(newUser)
print(self.userData)

case .failure(let error):
print(error)
break
}

Swifty Json parsing

The content of the "message" field is not parsed JSON, it's a JSON string.

Use SwiftyJSON's JSON(parseJSON:) initializer to accept a string as input and parse it as JSON:

let messages = json["data"]["messages"]["message"].stringValue
let innerJSON = JSON(parseJSON: messages)
let msg = innerJSON["data"]["msg"].stringValue // "HelloMsg"

How To Parse JSON with SwiftyJson

You're missing the conversion of the JSON to a JSON array using the Optional getters of SwiftyJSON and the JSON it's not interpreted as an array properly, so you need to use it like in the following code:

let jsonString = "[{\"mineral\": \"Phosphorus\",\"data\": [ 7.65, 19.74, 15.48 ]},{\"mineral\": \"Calcium\", \"data\": [ 1.65, 1.32, 1.78 ]}]"

if let dataFromString = jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) {
let json = JSON(data: dataFromString)

// Check if the JSON is an array otherwise nil
if let jsonArray = json.array {

var valuesB = [Double]()

for i in 0..<jsonArray.count {
print(jsonArray[i]["mineral"].stringValue)
print("Nutrient: \(json[i]["mineral"].stringValue)\n")

for j in 0..<jsonArray[i]["data"].count {
valuesB.append(jsonArray[i]["data"][j].doubleValue)
print("Values: \(jsonArray[i]["data"][j].doubleValue)")
}
}
}
}

And you should see in the console:

Phosphorus
Nutrient: Phosphorus

Values: 7.65
Values: 19.74
Values: 15.48
Calcium
Nutrient: Calcium

Values: 1.65
Values: 1.32
Values: 1.78

I hope this help you.

Parse JSON data with Swift, AlamoFire and SwiftyJSON

Can you try

if let result = response.result.value as? [String:Any] {
if let contact = result["contact"] as? [String:Any] {
if let first = contact["first"] as? String {
print(first)
}
}
}

also this

let data = JSON(data: JSON)

gives error because parameter should be of type Data not Dictionary

I would prefer to return Data from Alamofire request and use Decodable to parse it and convert to required model

How Can I Parse Json In Json With SwiftyJSON?

First, decode the main object.

Let's say data is the JSON in your question:

let json = JSON(data: data)

To get the content of the checklist key inside the array inside the checklists key, we can use SwiftyJSON's key path subscripting like this:

let checkList = json["checklists",0,"checklist"]
print(checkList)

Prints:

[{"title":"Test","summary":"Test 12"},{"title":"Test 2 ","summary":"Test 123"}]

This is your inner JSON as a String.

Make it data, then do the same process and access the array content:

if let json2String = checkList.string, 
data2 = json2String.dataUsingEncoding(NSUTF8StringEncoding) {
let json2 = JSON(data: data2)
let checkList2 = json2[0]
let title = checkList2["title"]
print(title)
}

Prints:

Test

Note that I've used key path subscripting for this example, but usual techniques like simple subscripting, loops and map/flatMap/etc also work:

let mainChecklists = json["checklists"]
for (_, content) in mainChecklists {
if let innerString = content["checklist"].string,
data2 = innerString.dataUsingEncoding(NSUTF8StringEncoding) {
let json2 = JSON(data: data2)
for (_, innerChecklist) in json2 {
let title = innerChecklist["title"]
print(title)
}
}
}

Prints:

Test

Test 2



Related Topics



Leave a reply



Submit