I have a json file to store all the messages in the application, for example :
{
"MSG_1": {
"en":"Something went wrong, please try again later",
"ar":"..."
},
"MSG_2": {
"en": "User created successfully",
"ar": "..."
},
"MSG_3": {
"en": "Phone number already exists",
"ar": "..."
},
"MSG_4": {
"en": "Validation Error, Fix it then try again",
"ar": "..."
}
}
- I extracted the josn into variable with this DataType
Dictionary<string, Dictionary<string, string>>
everything working fine to read the values from this json like this :jsonValues["MSG_1"]["en"]
With this way I faced some typo issues, I want to use this json as model and everytime I update the json file the model will update it self automaticlly.
I built something to fix the issue:
public class BusinessMessagesModel{
// I want to add some other Msg in this model automaticlly.
public MSGModel Msg {set; get;}
}
public class MSGModel{
public required string En {get; set;}
public required string Ar {get; set;}
}
I want to use the json file like this :
string value = businessMessagesModel.MSG_1.en;
Output : Something went wrong, please try again later
3
Answers
This seems like a very bad idea, but if you want to do it anyway you can write a source generator with a dependency on your json as an "additional file" that will build your models for you at compile time.
i would not suggest to store data in json due to usage you need at compile time.
so something like this string value = businessMessagesModel.MSG_1.en – will be available at compile time.
as a different approach i would suggest:
this is example to have class as enum which you can add messages at compilation and dynanicaly pick base on key name…
usage:
UPDATE:
another option is to use class as enumerator would be close to haw you want to use yours solution.
Without JSON
usage
Your structure when viewed as a table means for every new message, your adding a new column to the table. (and that’s why you have the mess of having to re-generate the class each time).
Why not make the Message ID a column like all the other fields?
Hence this:
So, now in code you can read/load the above into a list,
Say this class:
And now to load the above, we have this:
So, you address each message by a number, but you have to lookup, and know that number, so LITTLE advantages by using a column name for the message number.
The above is thus not only far more friendly, but allows you to pull such data into a List "of some class" item.
This will allow you to make a nice editor for all the messages, and editing, or adding new messages becomes rather simple.