C
C#9mo ago
Mekasu0124

✅ Can't figure out json logic

internal static int GetUsers()
{
try
{
var fileData = File.ReadAllText(_usersPath);
var jsonData = JsonSerializer.Deserialize<List<UserModel>>(fileData);

if (jsonData != null)
{
return jsonData.Count;
}
else
{
return 0;
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
internal static int GetUsers()
{
try
{
var fileData = File.ReadAllText(_usersPath);
var jsonData = JsonSerializer.Deserialize<List<UserModel>>(fileData);

if (jsonData != null)
{
return jsonData.Count;
}
else
{
return 0;
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
the purpose of this function is to simply return the number of users in the json file. The json file is structured like this
{
"something_here1": "something_here2"
}
{
"something_here1": "something_here2"
}
and I want to return the number of "something_here1"'s. Thanks in advance
43 Replies
Angius
Angius9mo ago
That's not a list {} in json denotes an object
Mekasu0124
Mekasu0124OP9mo ago
oh ok. so then do I need to iterate through the object, add the UserModel's to a list and then return the list count?
Angius
Angius9mo ago
You can't "iterate through object" Could also be a dictionary, I guess
{
"ThingOne": { ... },
"ThingTwo": { ... },
...
}
{
"ThingOne": { ... },
"ThingTwo": { ... },
...
}
could be a Dictionary<string, T> With T being, well, the type
Mekasu0124
Mekasu0124OP9mo ago
what about this?
public List<TodoItem> Load()
{
if (File.Exists(dbFile))
{
var dbInfo = File.ReadAllText(dbFile);

List<TodoItem> info = JsonSerializer.Deserialize<List<TodoItem>>(dbInfo);

return info;
}

else
{
return new List<TodoItem>();
}
}
public List<TodoItem> Load()
{
if (File.Exists(dbFile))
{
var dbInfo = File.ReadAllText(dbFile);

List<TodoItem> info = JsonSerializer.Deserialize<List<TodoItem>>(dbInfo);

return info;
}

else
{
return new List<TodoItem>();
}
}
Jimmacle
Jimmacle9mo ago
that doesn't change the fact the json isn't a list
Angius
Angius9mo ago
You cannot deserialize a not-list to a list
Jimmacle
Jimmacle9mo ago
it's a
class JsonThingy
{
string something_here1 { get; set; }
}
class JsonThingy
{
string something_here1 { get; set; }
}
or a dictionary like zzz said
Mekasu0124
Mekasu0124OP9mo ago
ok I think I got myself messed up a little bit so when the user is written to the json file, it's like this
{
"username": "password",
"username": "password",
...
}
{
"username": "password",
"username": "password",
...
}
that's done using a UserModel
Angius
Angius9mo ago
That would be a Dictionary<string, string> A dictionary of username-password pairs
Mekasu0124
Mekasu0124OP9mo ago
public class UserModel
{
public string? Username {get; set;}
public string? Password {get; set;}
}
public class UserModel
{
public string? Username {get; set;}
public string? Password {get; set;}
}
Angius
Angius9mo ago
No
Mekasu0124
Mekasu0124OP9mo ago
I said the wrong thing myfault
Angius
Angius9mo ago
[ // note the square brackets
{
"username": "Bob",
"password": "hunter12"
},
{
"username": "Stewie564",
"password": "hunter123"
},
]
[ // note the square brackets
{
"username": "Bob",
"password": "hunter12"
},
{
"username": "Stewie564",
"password": "hunter123"
},
]
Mekasu0124
Mekasu0124OP9mo ago
it's written like this
UserModel model = new()
{
Username = CreateUsername,
Password = ConfirmPassword
};

Dictionary<string, string> myDict = new()
{
{ model.Username, model.Password }
};

JsonEngine.InsertUser(myDict);
UserModel model = new()
{
Username = CreateUsername,
Password = ConfirmPassword
};

Dictionary<string, string> myDict = new()
{
{ model.Username, model.Password }
};

JsonEngine.InsertUser(myDict);
Angius
Angius9mo ago
This would deserialize to List<UserModel> So... a dictionary after all
Mekasu0124
Mekasu0124OP9mo ago
yes. I got mixed up
Angius
Angius9mo ago
Dictionary<string, string> myDict = new()
{
{ model.Username, model.Password }
// ^ key ^ value
};
Dictionary<string, string> myDict = new()
{
{ model.Username, model.Password }
// ^ key ^ value
};
or, clearer denoted as
Dictionary<string, string> myDict = new()
{
[model.Username] = model.Password
};
Dictionary<string, string> myDict = new()
{
[model.Username] = model.Password
};
Mekasu0124
Mekasu0124OP9mo ago
i didn't know I could do that
leowest
leowest9mo ago
I still don't understand why ur so focused on the json and not on your models if you control the json, then just worry about what your models look like
Mekasu0124
Mekasu0124OP9mo ago
ok. I wasn't consice enough with my issue. I'm trying to check the json file to see if any usernames exists, and if so then it's going to show screen A otherwise its going to show screen B which I believe I can do with a simple null check, right?
Angius
Angius9mo ago
Deserialize -> try to find -> see if found
leowest
leowest9mo ago
that's fine but u dont need to worry about what the json looks like if u control the models u know what you expect from your jsons to be
Mekasu0124
Mekasu0124OP9mo ago
ok. I'll try and remember that
Angius
Angius9mo ago
I guess the issue stems from the fact, that the users are serialized as username-password pairs Instead of user objects Which is confusing, since your first instinct when deserializing would be to try to deserialize it to a list of users
leowest
leowest9mo ago
if you're looking from the json perspective maybe @Mekasu0124 what I suggest to u is, create a console project and serialize different models and see what it looks like and then deserialize using the same models as a practice it will clear a lot of things you will notice a very clear pattern like when its {} and when its [] etc normally when you have no control over the json, its when u need to worry about what the json looks like to recreate the models and some APIs make it really nasty some times to the point where u need to use discriminators, unions, etc. but when you control the models you can model the json anyway u like so u dont have to worry about what it looks like as the final string so long as u make your models make sense to your needs.
Mekasu0124
Mekasu0124OP9mo ago
I wasn't concerned with the layout of the json file. I just showed what the file looked like as a reference with my issue I just want to be able to open the json file and see if it looks like {} or if it actually contains data and return a T/F value
leowest
leowest9mo ago
yes I understand that, and that showed us you dont understand the different json layouts for when u serialize something
Mekasu0124
Mekasu0124OP9mo ago
ok actually, I have another way I'm going to go about it. Thanks for the help guys
MODiX
MODiX9mo ago
leowest
REPL Result: Success
using System.Text.Json;
using System.Text.Json.Serialization;

JsonSerializer.Serialize<List<string>>(new List<string>())
using System.Text.Json;
using System.Text.Json.Serialization;

JsonSerializer.Serialize<List<string>>(new List<string>())
Result: string
[]
[]
Quoted by
<@1102729783969861782> from #bot-spam (click here)
Compile: 265.768ms | Execution: 25.067ms | React with ❌ to remove this embed.
leowest
leowest9mo ago
that is just an empty list serialized []
MODiX
MODiX9mo ago
leowest
REPL Result: Success
using System.Text.Json;
using System.Text.Json.Serialization;

Dictionary<string, string> myDict = new()
{
{ "username", "password" },
{ "username2", "password2" },
};
JsonSerializer.Serialize(myDict)
using System.Text.Json;
using System.Text.Json.Serialization;

Dictionary<string, string> myDict = new()
{
{ "username", "password" },
{ "username2", "password2" },
};
JsonSerializer.Serialize(myDict)
Result: string
{"username":"password","username2":"password2"}
{"username":"password","username2":"password2"}
Quoted by
<@1102729783969861782> from #bot-spam (click here)
Compile: 363.129ms | Execution: 34.200ms | React with ❌ to remove this embed.
leowest
leowest9mo ago
{
"username":"password",
"username2":"password2"
}
{
"username":"password",
"username2":"password2"
}
which was the example u provided above that is why I suggest the console app to try models at it will help u visualize better the json and the models
MODiX
MODiX9mo ago
leowest
REPL Result: Success
using System.Text.Json;
using System.Text.Json.Serialization;

var users = new List<User>
{
new User { Username = "username", Password = "password" },
new User { Username = "username", Password = "password" },
};

return JsonSerializer.Serialize(users);

public class User
{
public string Username {get;set;}
public string Password {get;set;}
}
using System.Text.Json;
using System.Text.Json.Serialization;

var users = new List<User>
{
new User { Username = "username", Password = "password" },
new User { Username = "username", Password = "password" },
};

return JsonSerializer.Serialize(users);

public class User
{
public string Username {get;set;}
public string Password {get;set;}
}
Result: string
[{"Username":"username","Password":"password"},{"Username":"username","Password":"password"}]
[{"Username":"username","Password":"password"},{"Username":"username","Password":"password"}]
Quoted by
<@1102729783969861782> from #bot-spam (click here)
Compile: 390.620ms | Execution: 51.849ms | React with ❌ to remove this embed.
leowest
leowest9mo ago
[
{
"Username":"username",
"Password":"password"
},
{
"Username":"username",
"Password":"password"
}
]
[
{
"Username":"username",
"Password":"password"
},
{
"Username":"username",
"Password":"password"
}
]
@Mekasu0124 anyway I just wanted to illustrate some of the differences, hope it helps u visualize things.
SoftwareEngineer666👿⸸⸸⸸
here i will show you how to do it. You can use DataContract and DataMember
SoftwareEngineer666👿⸸⸸⸸
This is a wrapper I made for Serializing and Deserializing objects to from json
SoftwareEngineer666👿⸸⸸⸸
if the outside of your json uses square brackets. That's a list or array right. So for example Suppose we have this class:
Mekasu0124
Mekasu0124OP9mo ago
I appreciate it but I’m actually going to use a database instead. It’s easier to work with
SoftwareEngineer666👿⸸⸸⸸
namespace Chat.Messages.Client.Messages { [DataContract] public class Example { [DataMember(Name = "username")] public string Username { get; protected set; } [DataMember(Name = "password")] public string Password { get; protected set; } } } suppose you have this json [{"username":"dfdffd", "password":"fdfddf"}, {"username":"anotheruser", "password":"dfdfdf"}] you could parse it like this new NativeJsonParser().Deserialize<Example[]> (theJsonString); 🙂 its really not. You're going to need json to speak to servers through websockets and for configuration files and stuff anyway 🙂
Mekasu0124
Mekasu0124OP9mo ago
what do you mean?
SoftwareEngineer666👿⸸⸸⸸
once you get the hang of parsing json using DataContract it's really easy. Just play with it till you get the hang of it :). When you write a class and decorate properties with DataMember you have to remember to provide a set method too. It requires that even if you're serializing it. You can make the set method protected. you can also nest objects with it. so a property in one class can be another class.
Mekasu0124
Mekasu0124OP9mo ago
lol I do good enough to create the avalonia project, and get basic functionality going on my applications 😂 I'm just toying around with the framework at this time. I'm not seriously producing anything, but I will keep this in mind and reference back to it when the time comes ❤️
SoftwareEngineer666👿⸸⸸⸸
Never used avalonia but it seems to be popular :). Ok
Want results from more Discord servers?
Add your server