I have a JSON file like the following:
[
{
"id": 123,
"textEN": "something",
"textDE": "irgendwas"
},
...
]
And I do have a struct in my environment:
struct Something: Codable, Identifiable, Hashable {
var id: Int
var text: String
}
What is the best and/or simplest way to only parse the language the user is using? I can check the users set language by using Locale.current.language.languageCode?.identifier
. But how should I always only parse the specific language?
I thought about the following approaches but stumbled across some problems:
- Parse all different languages and use a switch case within the view. Would work but is really really bad code in my opinion.
- Parse all different languages and implement another logical layer before the view. Before the data is being used by the view, a manager or view model or whatever will take care of removing all translations except the users one. Should work but is there a better option?
- Somehow only parse and store the one language from the data that is currently being used. Probably the best solution, but I was not able to get this one working. I tried to implement a CodingKey that’s a concatenated string ("text" + language code) but it is not possible, or at least I wasn’t able to figure out how, to use a variable as a CodingKey.
2
Answers
To parse only the language that the user is using, you can use the
init(from decoder: Decoder)
method of your Decodable struct to selectively decode only the language the user has set.Here is an example implementation:
In this implementation, you use the CodingKeys enum to define the keys for the properties in the JSON file. Then, in the
init(from decoder: Decoder)
method, you first get the user’s selected language, and then use it to selectively decode only the property that corresponds to the selected language.You can replace the default
language
value withLocale.current.language.languageCode?.identifier
to get the user’s selected language, but make sure to handle cases where the user’s language is not set or recognized.Hope this helps!
You could try this approach, using a dynamic key
AnyKey
(as mentioned in the comment and link),a
init(from decoder: Decoder)
and alangKey
to read only the language you want.The example code shows a very simple way
to read the json data with the use of a
class LingoModel: ObservableObject
.Adjust the code for your own purpose.