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

How to encode as an empty element #177

Closed
ksoftllc opened this issue Apr 24, 2020 · 2 comments
Closed

How to encode as an empty element #177

ksoftllc opened this issue Apr 24, 2020 · 2 comments
Assignees
Labels
more info needed Not enough details available to proceed

Comments

@ksoftllc
Copy link

ksoftllc commented Apr 24, 2020

I have a need to output an empty element, such as the PhoneNumbers element in this example:

<Person>
    <FirstName><![CDATA[BART]]></FirstName>
    <LastName><![CDATA[SIMPHSON]]></LastName>
    <Address1><![CDATA[122 ELMARCH AVE, CYNTHIANA, KY, 41031]]></Address1>
    <City><![CDATA[CYNTHIANA]]></City>
    <Zip><![CDATA[41031]]></Zip>
    <BirthDate><![CDATA[1950-05-01]]></BirthDate>
    <PhoneNumbers />
</Person>

Here is the struct:

struct Person: Encodable {
    let FirstName: String
    //. . .
    let PhoneNumbers: ???? //what goes here?
    //. . .
}

struct PhoneNumber: Encodable {
    let type: Int
    let number: String
}

I have tried the following values, but none appear in the encoded XML at all:

    let PhoneNumbers: [PhoneNumber] = []()
    let PhoneNumbers: [PhoneNumber]? = nil

I want the encoded XML to include the PhoneNumber element even when empty. Is that possible? If so, how?

Thanks!

@ksoftllc ksoftllc changed the title How to create empty element How to encode as an empty element Apr 24, 2020
@MaxDesiatov
Copy link
Collaborator

Hey @ksoftllc, have you tried something like this?

struct Person: Encodable {
    //. . .
    let PhoneNumbers: PhoneNumbers
    //. . .
}

struct PhoneNumbers: Encodable {
    enum CodingKeys: String, CodingKey { case items = "PhoneNumber" }
    let items: [PhoneNumber]
}

struct PhoneNumber: Encodable {
    let type: Int
    let number: String
}

This assumes that elements contained within a non-empty PhoneNumbers element are called PhoneNumber, I hope the code can be easily adjusted otherwise.

Does that resolve your issue?

@MaxDesiatov MaxDesiatov added the more info needed Not enough details available to proceed label Apr 27, 2020
@ksoftllc
Copy link
Author

That was the key. Problem solved. Thanks Max. Nice utility.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
more info needed Not enough details available to proceed
Projects
None yet
Development

No branches or pull requests

2 participants