How to parse JSON data with the same key and different data? - ios

I have a little problem with parse JSON data.
There have a Web API,basic response data like this:
{
topic_name: "Kevin",
topic_type: 1,
extraData: {}
}
With the different topic_type value, the extraData maybe have different data structure, e.g the extraData object has different key-values.
In this case, how to create model classes and parse the JSON string to models?
Or does this API design reasonable? Is there a better API design to solve these cases?
update 1:
With the same topic_type, the extraData's structure is always same.
I have considered use subclasses, but it need a subclass for every topic_type.
update 2:
Here is some example of JSON data, different topic_type with different extraData.
when topic_type equal to 1,
{
topic_name: "Kevin",
topic_type: 1,
extraData: {
data_type1: value,
data_type2: value2
}
}
when topic_type equal to 2,
{
topic_name: "David",
topic_type: 2,
extraData: {
data_type3: value3
}
}
it not real data, I'm not deal with a 'topic' issue, just a example, the key is the extraData object has different type keys.

JSONModel might be exactly what you're looking for. Parses json and gives you models

try to define all types in a class:
{
topic_name: "Kevin",
topic_type: 1,
extraData: {
data_type1: value,
data_type2: value2,
data_type3: value3,
}
}
after Json parsing, take the data types u need based on topic type.
Ps. All data types need to be nullable

Related

OpenAPI 3 Dictionary Define Key & Value Types

I have read https://swagger.io/docs/specification/data-models/dictionaries/, but am still having trouble modeling something like:
{
"top": {
"elem0": {
...
},
"elem1": {
...
},
...
}
}
top is a dictionary, containing an arbitrary number of entries. The trouble is that I want to define a reusable schema for the key and value types.
E.g., instead of saying that the keys are of type string, I say they are of type #/components/schemas/KEY. And instead of saying that the values are of type object, I say they are of type #/components/schemas/VALUE.
Is this possible?

Swift 5: getting several values out of JSON with array root object

I (a complete rookie) am currently trying to create my first iOS app - a currency table/converter for the currency of my country, Ukrainian Hryvna. I have created a TableView that I am going to fill with data from JSON file from the following link:
Tap here
The file itself has Array root. Like that:
[
{
"r030":36,"txt":"Австралійський долар","rate":21.334,"cc":"AUD","exchangedate":"23.12.2020"
}
,{
"r030":124,"txt":"Канадський долар","rate":21.9334,"cc":"CAD","exchangedate":"23.12.2020"
}
,{
"r030":156,"txt":"Юань Женьміньбі","rate":4.3192,"cc":"CNY","exchangedate":"23.12.2020"
}
,{
"r030":191,"txt":"Куна","rate":4.5833,"cc":"HRK","exchangedate":"23.12.2020"
}]
I want to get a create a Dictionary out of this file using just two values: [cc: rate] and then fill my TableView with this data. I don't care for other values.
Something like that:
["AUD": 21.334, "CAD": 21.9334]
Should I use some other data type to store this data? A Struct representing a currency and then make an Array of currency Structs, perhaps?
How do I get this file from that URL and make such a Dictionary/Struct array/...?
Thank you so much in advance :)
Make a struct
struct Currency : Decodable {
let name : String
let rate : Double
private enum CodingKeys : String, CodingKey { case name = "cc", rate }
}
Then load the data with URLSession and decode the JSON array to [Currency] with JSONDecoder (there are zillions of examples of both).

NSDictionary find keyPath

I have a random dictionary, I want to iterate over all objects that are inside that dictionary. Is there a way to find keyPath of object that is inside the dictionary?
Let's say we have this dictionary .
{
"glossary": {
"title": "example glossary",
"GlossDiv": {
"title": "S",
"GlossList": {
"GlossEntry": {
"ID": "SGML",
"SortAs": "SGML",
"GlossTerm": "Standard Generalized Markup Language",
"Acronym": "SGML",
"Abbrev": "ISO 8879:1986",
"GlossDef": {
"para": "A meta-markup language, used to create markup languages such as DocBook.",
"GlossSeeAlso": [
"GML",
"XML"
]
},
"GlossSee": "markup"
}
}
}
}
}
Now I want to find keyPath of GlossEntry or any other object.
Consider:
You can obtain all the keys in a dictionary and iterate over them. E.g. for (NSString *key in dictionary) {...}
Given a key you can obtain the matching value and test whether it is itself a dictionary.
Recursion is your friend. You could write a function which takes a current key path prefix, a dictionary, and a mutable array to add found key paths to. The implementation of this would involve (1), (2) and a recursive call.
Now write yourself some code. If you get stuck ask a new question, include your code, and explain where you are stuck.
HTH

Swift Sort Dictionary by property of an object value

I have a dictionary like <String,Loto> and Loto is object like below;
Loto:
{
"success": true,
"data": {
"oid": "64kbbqi8dbxygb00",
"hafta": 961,
"buyukIkramiyeKazananIl": "",
"cekilisTarihi": "11/04/2015",
"cekilisTuru": "SAYISAL_LOTO",
"rakamlar": "03#02#48#16#15#08",
"rakamlarNumaraSirasi": "02 - 03 - 08 - 15 - 16 - 48",
"devretti": false,
"devirSayisi": 0,
"bilenKisiler": [
{
"oid": "64kbbxi8dbxyg403",
"kisiBasinaDusenIkramiye": 7.35,
"kisiSayisi": 185712,
"tur": "$3_BILEN"
},
{
"oid": "64kbbxi8dbxyg402",
"kisiBasinaDusenIkramiye": 53.05,
"kisiSayisi": 9146,
"tur": "$4_BILEN"
},
{
"oid": "64kbbxi8dbxyg401",
"kisiBasinaDusenIkramiye": 4532.2,
"kisiSayisi": 142,
"tur": "$5_BILEN"
},
{
"oid": "64kbbxi8dbxyg400",
"kisiBasinaDusenIkramiye": 1528438.75,
"kisiSayisi": 1,
"tur": "$6_BILEN"
}
],
"buyukIkrKazananIlIlceler": [
{
"il": "10",
"ilView": "BALIKESÄ°R",
"ilce": "01001",
"ilceView": "AYVALIK"
}
],
"kibrisHasilati": 51127,
"devirTutari": 0.09,
"kolonSayisi": 10537872,
"kdv": 1599672.97,
"toplamHasilat": 10537872,
"hasilat": 8938199.03,
"sov": 893819.9,
"ikramiyeEH": 8044379.129999999,
"buyukIkramiye": 1528432.03,
"haftayaDevredenTutar": 0
}
}
So my dictionary like <"11042015",Loto> and i want to sort this dictionary by "hafta" property of loto object.
How can i do this? Please help me!
If Loto is an object with a hafta property, you can sort your dictionary by passing it into the sorted function, along with a closure that tells it how to order the entries:
sorted(dict) { $0.1.hafta < $1.1.hafta }
($0.1 and $1.1 because dictionaries present as a sequence of key/value pairs - you want to sort by a property of the value i.e. tuple entry 1)
Note, this will give you back a sorted array, of type [(String,Loto)] pairs, rather than a dictionary (as Swift dictionaries are unordered).
(if Loto is not really an object but rather another dictionary, you might need to do {$0.1["hafta"] < $1.1["hafta"]} - it really depends on how you’re holding your data - the good news is you don’t need to worry about optionals, since they can be compared with <)
If you don’t need the keys, just sort the values:
sorted(dict.values) { $0.hafta < $1.hafta }
which will give you back a sorted array of type [Loto]
Dictionaries are not ordered. What you need is to convert it to array, and then sort it. So something like this.
let lotoArray = lotoDictionary.allObjects as [Loto]
lotoArray.sort { $0.hafta < $1.hafta }
You can't. The keys of a dictionary are not sorted. You can get an array of the values and sort that array.

MongoMapper and custom type properties

I am trying to create a MongoMapper model which has an array of attributes. This array should contain all kind of information (Integers, Floats, URLs, Enums, Dates, Relations to other documents) depending on the user`s desire.
My problem is how implement the array of attributes, how to implement the custom data type of the attributes. I suppose that the document serialized should look similar to this:
{
...
attributes: {
age: {
name: "Age",
type: "Integer",
value: 12
},
height: {
name: "Height",
type: "Float",
value: 1.86
},
mother: {
name: "Mother",
type: "Relation\Person",
value: "\people\sara"
}
}
}
Any ideas how to approach this problem? My first tought was to create a base class like a factory which has to serialize and deserialize the attributes, but from what I have managed to code, nothing was working properly.
Thanks in advance!
You could make a custom type, but if you have an array, why not just use an embedded object?
See this:
http://speakerdeck.com/u/jnunemaker/p/mongomapper-mapping-ruby-to-and-from-mongo
Slides 47-49.

Resources