简体   繁体   中英

How can I get desired JSON structure after encoding in Swift

I have a struct name OpaqueData. I want to convert that object to JSON as in the following structure.

{
    "dataDescriptor": "Some Text",
    "dataValue": "Some Text"
                }

Strcut model of OpaqueData is as follows.

struct OpaqueData: Codable {

            let dataDescriptor: String

            let dataValue: String

        }

after encoding to json object dataValue property comes first and data descriptor comes second. How can I get desired JSON Structure after encoding strcut model to json.

let opaqueData = OpaqueData(dataDescriptor:"some text",dataValue: "some text")
let encodedData = try? JSONEncoder().encode(opaqueData)
let jsonString = String(data: encodedData!, encoding: .utf8)

print(jsonString!)

printed json string looks like this.

{
    "dataValue": "some text"

    "dataDescriptor": "some text",

                }

If you would like to output your json dictionary string ordered you need to set the encoder outputFormatting property to .sortedKeys :

struct OpaqueData: Codable {
    let dataDescriptor: String
    let dataValue: String
}

let opaqueData = OpaqueData(dataDescriptor:"some text", dataValue: "some text")

let encoder = JSONEncoder()
encoder.outputFormatting = .sortedKeys
let encodedData = try! encoder.encode(opaqueData)

let jsonString = String(data: encodedData, encoding: .utf8)!

print(jsonString)  // "{"dataDescriptor":"some text","dataValue":"some text"}\n"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM