0

Hello i am encoding array to json so that i have created model class like below

class QuotationListDataModel: Codable{
    var quatation_id: String?
    var PartNumber: String?
    var Description: String?
    var Quantity: String?
    var AvailableStockQty: String?
    var Each: String?
    init(quatation_id: String?, PartNumber: String?,Description: String?,Quantity:String?,AvailableStockQty: String?,Each: String?) {
        self.quatation_id = quatation_id
        self.PartNumber = PartNumber
        self.Description = Description
        self.Quantity = Quantity
        self.AvailableStockQty = AvailableStockQty
        self.Each = Each
    }

}

And the i am encoding like below

  let encoder = JSONEncoder()
  encoder.outputFormatting = .prettyPrinted
  do {
       let jsonData = try encoder.encode(quotationSeelctedData)
       if let jsonString = String.init(data: jsonData, encoding: .utf8) {
             print(jsonString)
       }
  } catch {
      print("the encoding failed")
  }

and with this code json encoded successfully but order not maintained when i print encoded string then i get output like below

[
  {
    "quatation_id": "67",
    "Description": "PSH BTN",
    "Each": "140.00 Total 40320.00",
    "PartNumber": "15",
    "Quantity": "288",
    "AvailableStockQty": "0"
  },
  {
    "quatation_id": "66",
    "Description": "SELF-CLOSING 4-ARM HANDLE (PLATED BRASS)",
    "Each": "14.00 Total 3612.00",
    "PartNumber": "000015-40",
    "Quantity": "258",
    "AvailableStockQty": "10"
  }
]

And i want output something like below

Part Number : 000015-40

Description : SELF-CLOSING 4-ARM HANDLE (PLATED BRASS)

Quantity : 10

Available Stock Qty. : 10

Each: 12.1 Total: 121

can any one tell me how to maintain order as per my model class has

Green
  • 15
  • 7
  • try this, encoder.outputFormatting = .sortedKeys and see what happen – Hatim Sep 27 '19 at 10:00
  • i already tried but still i am getting in wrong ordering – Green Sep 27 '19 at 10:01
  • Dictionaries are NOT ordered. You shouldn't care about order, it's a KEY access, not an INDEX access. So if it's because "Part Number" is not "the first one" to appear, that's normal behavior. – Larme Sep 27 '19 at 10:04
  • So is there any other solution for this? – Green Sep 27 '19 at 10:12
  • can I know why you want it ordered? I think the only order you can get is the alpha. order. – Hatim Sep 27 '19 at 10:22
  • because i am sharing this info in whats app through app this is the format for sharing in whats app – Green Sep 27 '19 at 10:27
  • Format it then. You don't want to share JSON, you want to share formatted output. Use a "transformer for that" in the order you want. – Larme Sep 27 '19 at 10:28
  • yes but there is not only one data there is multiple data shared in whats app so how to manage that – Green Sep 27 '19 at 10:31

1 Answers1

0

I guess, according to the comment above, you actually don't want to order the keys of the dictionary, you want the printed version is ordered as following:

Part Number : 000015-40
Description : SELF-CLOSING 4-ARM HANDLE (PLATED BRASS)
Quantity : 10
Available Stock Qty. : 10
Each: 12.1 Total: 121

so, I guess the correct answer here is to print it as following:

first, create wrapper

struct FailableDecodable<Base : Decodable> : Decodable {

    let base: Base?

    init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()
        self.base = try? container.decode(Base.self)
    }
}

let items = try JSONDecoder()
    .decode([FailableDecodable<QuotationListDataModel>].self, from: json)
    .compactMap { $0.base } // .flatMap in Swift 4.0

       }
  } catch {
      print("the encoding failed")
  }

print(items)

if you want to print them as you want

for item in items {
    print("Part Number : \(item.PartNumber!)" // << you should     handle it if it's nill, so use if let ...
    print("Description : \(item.Description!)"
    print("Quantity : \(item.Quantity!)"
    print("Available Stock Qty. : \(item.AvailableStockQty!)"
    print("Each: \(item.Each!) Total: \(item.AvailableStockQty! * item.Each!)"
}

Suggestion

I suggest you to follow swift code standards, and to protect your functions with defence programming - also, in your classes, don't ever your optional variables for required (important) information.

source:

https://stackoverflow.com/a/46369152/1388852

Hatim
  • 1,516
  • 1
  • 18
  • 30