#reading and writing to file.
1 messages ยท Page 1 of 1 (latest)
wdym
show your pom, and your project structure, what you used to run it, and the error, I'll make it work
It's okay, I don't need javaFX at this current moment, just need to be able to read/write data some how.. about to write a python script to do it for me and do a call from java
no
lemme ask you this
import org.json.simple.JSONObject;
wtf is this
so frustrating
first this is not jackson, second what's the problem ?
okay I have jackson-core-2.13.3.jar in my /lib folder in the directory
.... that's how i got it in the src file
yes. downloaded from Maven via IntelliJ
don't do that
how do?
sudo apt install maven?
you don't have maven installed ?
i do now mvn --version = 11.0.17
so it's here
also note that you do not need maven installed as long as you run from inside inetllij
yes
see.. the other class was taught how to do this, my class was not.
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.14.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.14.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.14.2</version>
</dependency>
' <url>https://github.com/FasterXML/jackson-core</url>
<scm>
<connection>scm:git:[email protected]:FasterXML/jackson-core.git</connection>
<developerConnection>scm:git:[email protected]:FasterXML/jackson-core.git</developerConnection>
<url>http://github.com/FasterXML/jackson-core</url>
<tag>jackson-core-2.13.3</tag>
</scm>
'
put this in the dependencies part
?
file is read only
the pom ?
do i need to add one to the src folder?
wdym
you have a pom at the root of the project
you just need to add the dependencies here
what's so complex ?
oh i thought it was java hahah
maven is a built tool and dependency manager
so file > new > project > build system Maven
instead of doing everything yourself, or even letting your ide do it, you use maven
yes
it beeps me
?
<dependencies> must be in <project>
intellij should be able to autocomplete this for you
now it is giving me an error on the version
beautiful !
that's probably what I am missing with the JavaFX stuff too , just have a feeling
and do this manipulation if it whines again
I mean, copy paste what I shared before
for sure.
so now how to import jackson or is it in there already, or better yet can you point me to a dummy friendly tutorial?
wow it's all in there ๐
String json = """
{
"name": "Henry",
"age": 19
}""";
ObjectMapper mapper = new ObjectMapper();
Person person = mapper.readValue(json, Person.class);
//User person
String newJson = mapper.writeValueAsString(person);
println(newJson);
Person being like
class Person {
String name;
int age;
}
//or
record Person(String name, int age) {}
I wrote it in discord so idk if it will work
@tender perch
which error ?
java: no suitable method found for readValue(org.example.Person)
I added the class..
ah my bad
fixed
it builds, but will not run
wdym
it makes me add throws json error because of readvalue,
wdym
?
Exception in thread "main" com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "name" (class org.example.Person), not marked as ignorable (0 known properties: ])
at [Source: (String)" {
"name": "Henry",
"age": 19
}"; line: 2, column: 14] (through reference chain: org.example.Person["name"])
three ways
either use a record
or add annotations on the fields of Person
or add a constructor and an annotation on this constructor in Person
hmm
can you show your Person class please just in case ?
yes.
that is it.
so I can make that class abstract and extend, and give it an interface for it's methods right
I have to refactor what I already have into this, but it shouldn't be too hard
why
you don't need that
just make a class for each thing you want to save
then either you save in separate files or you create another class which will hold those classes
also
if you will go for correct oop
fields should be private, with constructor and getters
and then
you can tell jackson to specifically use a constructor instead of directly assigning to the fields by using @JsonCreator annotation
@tender perch
I still need to write it to a file too, correct?
wdym
in order to keep data static between runs
my goal is to register a user with appropriate fields, and have that data kept and referenced in order to "log in"
I think I can work with this though
i don't see the problem
no problem, just need to read and write the json from a file instead of hardcoding
jackson directly has methods for that btw, if you look at the doc
the last chapter was on decorators, it seems like that is what jackson is all about huh
decorators ?
ya decorator pattern.
i feel like you would get waaaay more from this book than I do, you should check it out HeadFirst Design Patterns
it's good, all headfirst is good stuff
this is unrelated to decorator pattern ๐ค
lol yeah.. i'm lost friend thanks for your help
yes. This is working out pretty well to store the objects. thank you so much! I am just loading it from the file as one String.
@smoky narwhal you still there? I am trying to do the same thing you showed me but instead it links username to it's fields so I can have a single file hold many user data, but not sure how to name the fields
{"jeffro123":{"password":"Password123","UserName":"jeffro123","name":"jeffro","isAdmin":"Password123","age":38}} is what I am writing
you see the first field doesn't have a name , just "jeffro123"
Exception in thread "main" com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "jeffro123" (class org.example.CurrentRegistry), not marked as ignorable (0 known properties: ])
wait... i just have to name the variables right
fields rather..
So Jackson thinks that jeffro123 is supposed to be a field when it's actually the username
May I ask why are you storing data like this?
Why do you have an object with a field name as the username, and the object it equals is all the data?
it's both a field and a username, from what I see
Yeah
appears 2 times
But why are they storing jt like this
You should be doing
{"password":"Password123","UserName":"jeffro123","name":"jeffro","isAdmin":"Password123","age":38}
Also u should never directly store passwords
"isAdmin":"Password123"

Use a hash and store the hashes
Oh that too is wrong then ig
yo
sorry i think i figured it out
i know
that is on my //todo
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
and that was a typo the password123. obviously I am a master programmer lolll
So you fixed your object structure?
No that is not how you would do it
well that fixed the problem at least, I would rather map that first field to a name like username
Yeah keep the first field the username
Do it like this but username first
And change ur class accordingly
Also don't store passwords directly
Use hashes
now I am trying to instantiate a user object off of those stored fields
and i will def implement some sha256 or better for those passwords, this is the first sprint
and it's due tomorrow XD
If someone obtains ur json file they would get the passwords kf all users
But if u use hashes they would be meaningless to them
Do you know how yo use the object mapper?
i am acutely aware of this fact, thank you, it should be easy to do
Yes
i'm just now figuring that out
Could you just send your class here
So we can know that u have implemented it correctly
I was talking about your pojo
The class where you represent the user data
so far it is working like a dream.
Ok, it is better to use annotations tho
System.out.println(currentRegistry.mapByUserName.get("jeffro123").get("password"));
i have to access them like this, but that should be enough to get it going
example of anotations?
Ok so hold on
Ur current registry holds all the users
yes
And u use usernames as keys?
yes.
to this point yes, and ACL kind of info
was hoping to have time to gpg the file, hash teh passwords and have a gui lol
Not sure if that's the best way to go about it
I mean what u are doing either custom registry
You should be able to use ur data holders like java objects
the json fields populate the user object instance variables is what I am hoping to do
Maybe you could use a map
With username as key and other stuff as a value
Not sure how to annotate ur class to gl aboutnit
Map<String, Map<String, Object>> mapByUserName = new HashMap<>();
It would be Map<String, User>
Because currently ur user class isn't doing anything
For the json
it is something I can bug my teacher about after I turn it in. I have worked very hard to keep his expectations low
yeah you are right
Look I gtg, I'll try to get back later
user object right
okay i will try that out thanks!
i see exactly what you mean and that is where i have been hung up since i got the other field to work out thanks!
so my data looks like this now, ```[{"jeffro123":{"password":"Password123","UserName":"jeffro123","name":"jeffro","isAdmin":true,"age":38}},
{"fr3d":{"password":"wilma412","UserName":"fr3d","name":"fred f","isAdmin":false,"age":38}}]``````````
but I can't access either of them. it says java.util.LinkedHashMap<java.lang.Object,java.lang.Object>from Array value (token JsonToken.
woah i see @NotNull on my intellij now
Use a map
Yes you have a list in the json
By reading it ?
i have another class like the User class you showed me for the Registry class and that works the same way, just need to open up that list. should i just replace the [ ] with {}
No
Use a list or array in java
You have a list in json
You need to have a list java
You can't transform it in something else, that doesn't make sense
{"fr3d":{"password":"wilma412","UserName":"fr3d","name":"fred f","isAdmin":false,"age":38}}]``````
Also why do you have a list in the json actually?
public Map<Object[], Map<String, Object>> mapByUserName = new HashMap<>(); is what I am trying to bring it in to
No
it gave me an error
Don't do that
Don't use Objet
Use specific classes
Like we did yesterday
And why do you need this list ?
Why in the json, you have a list of maps of objects
@tender perch
because it gave me an error when I tried to just have 2 of them in there
omfg
thats all i had to do
Two what, maps ? Why do you want two ?
it works i think...
Tell me that you didn't use Object
Also format your json please
String testUserName1 = "jeffro123";
String testUserName2 = "fr3d";
ObjectMapper mapper = new ObjectMapper();
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
//BusinessAdmin jeffro = mapper.readValue(json, BusinessAdmin.class);
CurrentRegistry currentRegistry = new CurrentRegistry();
currentRegistry.mapByUserName = mapper.readValue(json, Map.class);
User fred = new User();
fred.inflateUser(currentRegistry.mapByUserName.get(testUserName2), fred, "fr3d");
User jeffro = new User();
jeffro.inflateUser(currentRegistry.mapByUserName.get(testUserName1), jeffro, "jeffro123");
System.out.println(jeffro.password);```
Detected code, here are some useful tools:
public static void main(String[] args) throws IOException {
String testUserName1 = "jeffro123";
String testUserName2 = "fr3d";
ObjectMapper mapper = new ObjectMapper();
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
//BusinessAdmin jeffro = mapper.readValue(json, BusinessAdmin.class);
CurrentRegistry currentRegistry = new CurrentRegistry();
currentRegistry.mapByUserName = mapper.readValue(json, Map.class );
User fred = new User();
fred.inflateUser(currentRegistry.mapByUserName.get(testUserName2), fred, "fr3d");
User jeffro = new User();
jeffro.inflateUser(currentRegistry.mapByUserName.get(testUserName1), jeffro, "jeffro123");
System.out.println(jeffro.password);
Show the json formatted Please
{"fr3d":{"password":"wilma412","UserName":"fr3d","name":"fred f","isAdmin":false,"age":38}}```
thats what i have now
and i can call in jeffro123, but not fr3d
Please format it
It's unreadable
"jeffro123": {
"password": "Password123",
"UserName": "jeffro123",
"name": "jeffro",
"isAdmin": true,
"age": 38
}
}```
fr3d disappears...
Where is fr3d here ?
he's gone!!
he is here though
It's not formatted
Please format the json so I can read it
{"jeffro123" : {"password" : "Password123" , "UserName" : "jeffro123" , "name" : "jeffro" , "isAdmin" : true , " age " : 38}}
{"fr3d" : {"password" : "wilma412" , "UserName" : "fr3d" , "name" : "fred f" , "isAdmin" : false , " age " : 38}}
is that better?
when i put brackets [ ] and a comma , between the two, it works in the online format tool
{
"jeffro123": {
"password": "Password123",
"UserName": "jeffro123",
"name": "jeffro",
"isAdmin": true,
"age": 38
}
},
{
"fr3d": {
"password": "wilma412",
"UserName": "fr3d",
"name": "fred f",
"isAdmin": false,
"age": 38
}
}
]```
Right
So as you see here
You need an array at the outside
Then a map
Then individual objects
so i need a list(map(string:map))
No
java has list?
java has pretty much everything u could think of. it has one of the richest standard libs
Map<String, User>[]
Or
List<Map<String, User>>
Wait a minute why do you have an object with a single attribute here
You don't need the list nor the outer objects
i am using that to instantiate the object
How is that related
Jackson has certain annotations
Why do you have single element objects in the json
so the file stores those fields by username, i search for username then take the fields, and shove them into the "inflateObject" method i created
Unrelated here
The problem is that the json doesn't make sense
They want to create a username to user mapping
Why do you have a list of objects of single element of objects when you can have a map of the objects
Oh they do an additional layer of wrapping into objects
@tender perch
Yeah that is not needed
Two levels
https://paste.pythondiscord.com/igiduvukep here's what i'm working with
{
"jeffro123": {
"password": "Password123",
"UserName": "jeffro123",
"name": "jeffro",
"isAdmin": true,
"age": 38
},
"fr3d": {
"password": "wilma412",
"UserName": "fr3d",
"name": "fred f",
"isAdmin": false,
"age": 38
}
}
@tender perch your json should look like this
kk lemme see what i can do
Also why are you using a map in a map?
because i want to reference the values by their key
Just use Map<String, User> like i told u before
i tried, but the json being wrong made it not work
Yeah so username to user mapping just needs string as keys and user as values
exactly
The json Alathreon sent would work, just you might have to add some annotations I think
so hard to type it like that
this is going to present another problem when it writes it back into the file isnt it
ohh string user
i was wondering what object to call the values in there.. it is all the values of the user though
Ah
Well I created a class to store all user values
Called user
So you use that class for the values
i have User class
i hate user class.. only works for jeffro
truth be told I am really bad at this
o m g
it works
yo that Map<String, User> stuff is on point
I have been trying to get this to work for 14 hours now.
you see how I am using cReg (which is the map ) sort of as a constructor? is this really bad practice?
Kinda yeah....
Why don't u just let Jackson do it's thing
And directly populate users into a map
https://www.baeldung.com/jackson-map
Take a look at this
No
You don't need annotations
That's wrong, directly ask Jackson to get a Map<String, User>
was just looking at the @rustic kiteAnyGetter is that going to accomplish the same thing?
i just let intellij encapsulate everything for me, and doing it the way I did in the pic, now every damn thing has a getter and setter
this code looks I am writing looks a lot like python, and it is working very well. thanks both of you for your help
do I even need a getter and setter with those fields? I am now reading it properly as a Map<String, User>
You are not supposed to use that
oh lol
You are just supposed to let Jackson parse as Map of strings and users
i gotta scroll way back up for that you already showed me once, but i been fighting it all day and think i may have deleted that line.
The only difficult part is to manage to tell it to correctly handle the Map generics
Which can be done with TypeReference
You changed the json ?
no
Why are you only reading one user now?
I have 2, just trying to build fred the way you are suggesting
currentRegistry.getMap() returns the Map<String, User>
Wait why are you trying to read that, why don't you use the file ?
it is already read into the currentRegistry object
store variables in a convenient way
oh
You need to read it as a map with type reference
ObjectMapper mapper = new ObjectMapper();
currentRegistry.setMapByUserName(mapper.readValue(json, Map.class));
Don't do that
You obtain a raw map
Not only this is bad, and intellij should warn you
But then you also have to convert everything yourself
Instead use a type reference
readValue(json, new TypeReference<Map<String, User>>(){})
type reference eh..
User fred = mapper.readValue(json, new TypeReference<Map<String,User>>(){});
This return a Map<String, User>
it wanted me to cast it to type User
You can't
oh
from this line? mapper.readValue(json, new TypeReference<Map<String,User>>(){});
Yes
This simply parse the json
get out of town
?
yeah..
well
i guess it works..
but how do I use the objects tho
gonna stick with what I had before for now, I have to have something to turn in.
i have to stop now though.. time for sleep so I can get up early and finish it
Wdym
You now have the map
Then you can use it
the way I have it set up, i instantiate the object using the json so then i can say User jeff = new User(); then I can say jeff.setPassword() etc
But everything is already done
i had to comment nearly all of my code too lol
You don't need to do any of that
so I build my 2 user objects jeffro and fred, how do i say fred.coolMethod()?
Yes but note that you just needed to follow what I said yesterday and directly read the json into an user, like we did yesterday, I don't understand why you got rid of that to then do everything manually
Get Fred from the map and then call whatever method
because the json wasn't working for me remember
It was
It's just that you changed it
yes it was until I changed the
yes exactly.
thank you, sorry you are absolutely right.
however, i had to change it to fit my needs and it seems to be working great
any, i gotta try to get some slee. I have something that kind of works right now, should be pretty easy to hack the rest together, then I can dial in the JSON.. assuming i can write to a file. I think I need to use the PrettyPrint from Jackson.
Thanks again
Yeah I wasn't sure if annotations were needed or not
Parsing to a list needs annotations so I thought this might too
No it doesn't
No that's not what I mean, Instead of trying to make it work and understand why it didn't, you tried to avoid the problem by totally changing the way it worked to end up with something way worse
That's why I am asking you to fix that
Also Jackson can read a file itself
Laying in bed trying to sleep last night I think I got a better understanding. The map generated will have the users in it and I can access those users by saying map.get("username")
hahahaha NEAT
yes
I fix it, thank you
I never understood JSON, now I think I get why it is called OBJECT NOTATION haha
why do you store the json in a field and why do you have a whole method for that ?
that is reading the JSON from a file as a String. IntelliJ told me to put the try/catch for it
yes but it should be a one liner, you don't need a whole method for that
and you shouldn't store the json in a field
also jackson can directly read a file, no need to do that
fixed.
well at least mostly fixed, I still have the method to read it.
I am running out of code to commit!
all that bloated stuff I wrote yesterday got deleted
this is so awesome though way more than I would have anticipated, hopefully I can talk the group into using this
stupid group projects..
you really gave me a reason to enjoy working on this project though. The others have all made a fake login/registry, but this one will actually work like a real world app almost
finally ready to write objects back to the the file.