2

I am using JSONDecoder to save my JSON data into objects. But I would like some part of the JSON to be saved as is. Is that possible?

Say this is my JSON

"customer": {  
     "personal": {  
        "name": "John Doe",  
        "misc": {  
            "active": “true”,  
            "addons": {  
              "country": "USA",
              "state": "Michigan"
            },  
        "customer_id": "1234"   
        }    
    },  
    "source": "main"  
}

And I map all data as

class Customer {  
   let personal: Personal
   let source: String  
}   

class Personal {  
    let name: String
    let customer_id: String 
    let misc: String // I want this to be saved as just raw json
} 

How can I parse the JSON so that misc is saved as just raw JSON which I can use later?

user3539959
  • 383
  • 3
  • 15
  • 1
    no there is no way too – Shehata Gamal Nov 23 '20 at 13:09
  • Override `init(from decoder:)` and set the value as a String? But defined "as raw JSON", be – Larme Nov 23 '20 at 13:09
  • What do you mean by "which I can use later?" Do you mean you just want it as a string (like you've done here)? Or do you mean you want to query values from it? (Which wouldn't be a string.) Or do you mean you want to be able to round-trip it back to JSON without manipulating it? – Rob Napier Nov 23 '20 at 15:00
  • I'm asking to determine if this is a duplicate of this question: https://stackoverflow.com/a/48571156/97337 If not, let me know what's different and we can discuss that. – Rob Napier Nov 23 '20 at 15:04
  • @RobNapier I wish to save it as a raw JSON (whether data or string) and use `JSONSerialization` on it later when I need to read the data. The JSON data will be a dictionary with variable keys so I don't want to create a Codable for it – user3539959 Nov 24 '20 at 04:56
  • Check the above linked answer. It can handle storing and querying arbitrary JSON without resorting to JSONSerialization. If that doesn't work, update the question with the issue, and there are other approaches, typically with custom Decodable implementations. – Rob Napier Nov 25 '20 at 17:00

0 Answers0