Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow to create JSON object from any Encodable object, and to decode into a Decodable object conveniently #963

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

catjia1011
Copy link

This pull request provides a convenient way for SwitfyJSON to integrate with other Codable objects.

example:

struct Student: Codable {
    let id: Int, name: String
}

let student = Student(id: 1, name: "Bill")
let json = JSON(parseEncodable: student)
print(json.rawString(.utf8, options: [])!) // {"id":1,"name":"Bill"}
print(json.decode(Student.self)!.name) // Bill

@toohotz
Copy link

toohotz commented Jul 3, 2019

Not sure if something like this is still of interest since this PR is more than a year old but I had done something similar when used to encrypt and decrypt Codable objects and you're probably going to want an additional parameter for a custom JSONDecoder and JSONEncoder for those using a custom structure.

@@ -131,6 +131,22 @@ public struct JSON {
}
}

/**
Parses the object confirming to Encodable protocol into a JSON object using JSONEncoder
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I assume you meant conforming here slight keystroke mixup since "i" and "o" are next to each other 😉

@q240252859
Copy link

q240252859 commented Apr 30, 2020

var json: JSON = ["name": "25.22", "age": 25.0023]
print(json)
{
"age" : 25.002300000000002,
"name" : "25.22"
}

  • rawArray : 0 elements
    ▿ rawDictionary : 2 elements
    ▿ 0 : 2 elements
    • key : "age"
    • value : 25.0023
      ▿ 1 : 2 elements
    • key : "name"
    • value : "25.22"
  • rawString : ""
  • rawNumber : 0
  • rawNull :
  • rawBool : false
  • type : SwiftyJSON.Type.dictionary
  • error : nil

@q240252859
Copy link

var json: JSON = ["name": "25.22", "age": 25.0023]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

3 participants