#reading and writing to file.

1 messages ยท Page 1 of 1 (latest)

tender perch
#

ya downloaded from Maven in intellij

smoky narwhal
#

wdym

#

show your pom, and your project structure, what you used to run it, and the error, I'll make it work

tender perch
#

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

smoky narwhal
tender perch
#

lemme ask you this

#

import org.json.simple.JSONObject;

#

wtf is this

#

so frustrating

smoky narwhal
tender perch
#

okay I have jackson-core-2.13.3.jar in my /lib folder in the directory

smoky narwhal
#

why

#

don't do that

#

use maven

tender perch
#

.... that's how i got it in the src file

smoky narwhal
#

no

#

you are not supposed to manually download libs

tender perch
#

yes. downloaded from Maven via IntelliJ

smoky narwhal
#

don't do that

tender perch
#

how do?

smoky narwhal
#

use maven

#

put the dependency in the pom

#

and it will work

tender perch
#

sudo apt install maven?

smoky narwhal
#

you don't have maven installed ?

tender perch
#

i do now mvn --version = 11.0.17

smoky narwhal
#

so it's here

#

also note that you do not need maven installed as long as you run from inside inetllij

tender perch
#

so add dependency, to pom.xml?

#

what is dependency for jackson

smoky narwhal
tender perch
#

see.. the other class was taught how to do this, my class was not.

smoky narwhal
#
<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>
tender perch
smoky narwhal
#

put this in the dependencies part

tender perch
#

file is read only

smoky narwhal
tender perch
#

do i need to add one to the src folder?

smoky narwhal
#

wdym

#

you have a pom at the root of the project

#

you just need to add the dependencies here

#

what's so complex ?

tender perch
#

where is pom?

#

also, you have the patience of a saint.

smoky narwhal
#

you need a maven project to use maven

tender perch
#

oh i thought it was java hahah

smoky narwhal
#

maven is a built tool and dependency manager

tender perch
#

so file > new > project > build system Maven

smoky narwhal
#

instead of doing everything yourself, or even letting your ide do it, you use maven

#

yes

tender perch
#

oh ya ya ya i see the pom file!

#

okay so i added dependencies

smoky narwhal
#

no

#

you must put them in a <dependencies> node

#

here you put them in <project>

tender perch
#

wow

#

it's really gonna make me type it all by hand. I hope this works

smoky narwhal
#

wdym

#

just copy paste

tender perch
#

it beeps me

smoky narwhal
#

?

tender perch
#

got it typed anyway, okay

#

error right at the first <dependencies>

smoky narwhal
#

<dependencies> must be in <project>

#

intellij should be able to autocomplete this for you

tender perch
#

now it is giving me an error on the version

smoky narwhal
#

right click the pom

#

maven

#

reload maven project

tender perch
#

beautiful !

#

that's probably what I am missing with the JavaFX stuff too , just have a feeling

smoky narwhal
#

and do this manipulation if it whines again

smoky narwhal
tender perch
#

for sure.

smoky narwhal
#

anyway

#

now try jackson

#

in your main :

tender perch
#

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 ๐Ÿ™‚

smoky narwhal
#
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

tender perch
#

typing it in

#

yeah it doesn't seem to work

#

Person.class is giving an error

smoky narwhal
tender perch
#

java: no suitable method found for readValue(org.example.Person)

#

I added the class..

smoky narwhal
#

ah my bad

tender perch
#

""" Person person = mapper.readValue(Person.class);
"""

#

that line

smoky narwhal
#

fixed

tender perch
#

it builds, but will not run

smoky narwhal
#

wdym

tender perch
#

it makes me add throws json error because of readvalue,

smoky narwhal
#

wdym

tender perch
#

haha im stupid. i had public static void Main.

#

that doesnt work so well

smoky narwhal
#

?

tender perch
#

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"])

smoky narwhal
#

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 ?

tender perch
smoky narwhal
#

hmm

#

retry by setting name and age as public

tender perch
#

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

smoky narwhal
#

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

tender perch
#

I still need to write it to a file too, correct?

tender perch
#

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

smoky narwhal
#

i don't see the problem

tender perch
#

no problem, just need to read and write the json from a file instead of hardcoding

smoky narwhal
tender perch
#

the last chapter was on decorators, it seems like that is what jackson is all about huh

tender perch
#

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

smoky narwhal
tender perch
#

lol yeah.. i'm lost friend thanks for your help

tender perch
#

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.

tender perch
#

@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..

full pond
#

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?

vast crow
#

it's both a field and a username, from what I see

full pond
#

Yeah

vast crow
#

appears 2 times

full pond
#

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

vast crow
#

"isAdmin":"Password123"
thonk

full pond
#

Use a hash and store the hashes

full pond
tender perch
#

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

full pond
#

So you fixed your object structure?

full pond
tender perch
#

well that fixed the problem at least, I would rather map that first field to a name like username

full pond
#

Yeah keep the first field the username

full pond
#

And change ur class accordingly

#

Also don't store passwords directly

#

Use hashes

tender perch
#

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

full pond
full pond
tender perch
#

i am acutely aware of this fact, thank you, it should be easy to do

full pond
#

Yes

tender perch
#

i'm just now figuring that out

full pond
#

Could you just send your class here

#

So we can know that u have implemented it correctly

tender perch
#

stupid popup blocked the good parts

full pond
#

I was talking about your pojo

tender perch
#

i keep seeing that word pojo

#

oh ya

full pond
#

The class where you represent the user data

tender perch
#

not much so far

#

no getters no setters

full pond
#

You haven't used any annotations either

#

Is it still working?

tender perch
#

so far it is working like a dream.

full pond
#

Ok, it is better to use annotations tho

tender perch
#

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?

full pond
#

Ur current registry holds all the users

tender perch
#

yes

full pond
#

And u use usernames as keys?

tender perch
#

yes.

full pond
#

And then that contains all their data

#

Hmm

tender perch
#

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

full pond
#

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

tender perch
#

the json fields populate the user object instance variables is what I am hoping to do

full pond
#

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

tender perch
#

Map<String, Map<String, Object>> mapByUserName = new HashMap<>();

full pond
#

It would be Map<String, User>

#

Because currently ur user class isn't doing anything

#

For the json

tender perch
#

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

full pond
#

Look I gtg, I'll try to get back later

tender perch
#

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!

tender perch
#

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.

tender perch
#

woah i see @NotNull on my intellij now

smoky narwhal
tender perch
#

ya can't figure out how to read the list in

#

so close to doing what i want it to

smoky narwhal
tender perch
#

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 {}

smoky narwhal
#

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

tender perch
#
{"fr3d":{"password":"wilma412","UserName":"fr3d","name":"fred f","isAdmin":false,"age":38}}]``````
smoky narwhal
#

Also why do you have a list in the json actually?

tender perch
#

public Map<Object[], Map<String, Object>> mapByUserName = new HashMap<>(); is what I am trying to bring it in to

smoky narwhal
#

No

tender perch
#

it gave me an error

smoky narwhal
#

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

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

smoky narwhal
#

Two what, maps ? Why do you want two ?

tender perch
#

it works i think...

smoky narwhal
tender perch
#

well

#

it almost works..

smoky narwhal
#

Also format your json please

smoky narwhal
#

Please get rid of Objet

tender perch
#
        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);```
ruby dirgeBOT
# tender perch ``` public static void main(String[] args) throws IOException { Strin...

Detected code, here are some useful tools:

Formatted code
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);
smoky narwhal
#

Show the json formatted Please

tender perch
#
{"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

smoky narwhal
#

It's unreadable

tender perch
#
   "jeffro123": {
      "password": "Password123",
      "UserName": "jeffro123",
      "name": "jeffro",
      "isAdmin": true,
      "age": 38
   }
}```
#

fr3d disappears...

smoky narwhal
tender perch
#

he's gone!!

tender perch
smoky narwhal
#

Please format the json so I can read it

tender perch
#

{"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
      }
   }
]```
smoky narwhal
#

Right

#

So as you see here

#

You need an array at the outside

#

Then a map

#

Then individual objects

tender perch
#

so i need a list(map(string:map))

smoky narwhal
#

No

#

List map your specific class your created

tender perch
#

User[]

#

you mean array?

smoky narwhal
#

No

tender perch
#

java has list?

proven fjord
#

java has pretty much everything u could think of. it has one of the richest standard libs

smoky narwhal
#

Map<String, User>[]
Or
List<Map<String, User>>

smoky narwhal
#

You don't need the list nor the outer objects

tender perch
#

i am using that to instantiate the object

smoky narwhal
#

How is that related

full pond
#

Jackson has certain annotations

smoky narwhal
#

Why do you have single element objects in the json

tender perch
#

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

full pond
#

Which allow u to read objects into maps and lists

#

Without having to do any work

smoky narwhal
full pond
#

They are supposed to use a map

#

Right?

smoky narwhal
#

The problem is that the json doesn't make sense

full pond
#

They want to create a username to user mapping

smoky narwhal
#

Why do you have a list of objects of single element of objects when you can have a map of the objects

full pond
#

Oh they do an additional layer of wrapping into objects

smoky narwhal
#

@tender perch

full pond
#

Yeah that is not needed

smoky narwhal
tender perch
smoky narwhal
#
   {
      "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

tender perch
#

kk lemme see what i can do

full pond
#

Also why are you using a map in a map?

tender perch
#

because i want to reference the values by their key

full pond
#

Just use Map<String, User> like i told u before

tender perch
#

i tried, but the json being wrong made it not work

full pond
tender perch
#

exactly

full pond
tender perch
#

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

full pond
#

Ah

#

Well I created a class to store all user values

#

Called user

#

So you use that class for the values

tender perch
#

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?

full pond
#

Kinda yeah....

#

Why don't u just let Jackson do it's thing

#

And directly populate users into a map

smoky narwhal
smoky narwhal
tender perch
#

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>

smoky narwhal
tender perch
#

oh lol

smoky narwhal
#

You are just supposed to let Jackson parse as Map of strings and users

tender perch
#

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.

smoky narwhal
#

The only difficult part is to manage to tell it to correctly handle the Map generics

#

Which can be done with TypeReference

tender perch
#

testUserName2 = fr3d

smoky narwhal
#

You changed the json ?

tender perch
#

no

smoky narwhal
#

Why are you only reading one user now?

tender perch
#

I have 2, just trying to build fred the way you are suggesting

smoky narwhal
#

And directly read as a map

tender perch
#

currentRegistry.getMap() returns the Map<String, User>

smoky narwhal
#

But in order to return

#

You first need to read it

smoky narwhal
tender perch
#

it is already read into the currentRegistry object

smoky narwhal
#

Wait no that doesn't make sense

#

User isn't a json

#

What are you trying to do?

tender perch
#

store variables in a convenient way

smoky narwhal
#

?

#

I am talking about reading json

tender perch
#

oh

smoky narwhal
#

You need to read it as a map with type reference

tender perch
#

ObjectMapper mapper = new ObjectMapper();

#

currentRegistry.setMapByUserName(mapper.readValue(json, Map.class));

smoky narwhal
#

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>>(){})

tender perch
#

type reference eh..

#

User fred = mapper.readValue(json, new TypeReference<Map<String,User>>(){});

smoky narwhal
tender perch
#

it wanted me to cast it to type User

smoky narwhal
#

You can't

tender perch
#

lol right

#

how do i build the object from the map?

smoky narwhal
#

It is already built

#

You already have the map of users

tender perch
#

oh

#

from this line? mapper.readValue(json, new TypeReference<Map<String,User>>(){});

smoky narwhal
#

This simply parse the json

tender perch
#

get out of town

smoky narwhal
#

?

tender perch
#

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

smoky narwhal
#

You now have the map

#

Then you can use it

tender perch
#

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

smoky narwhal
#

But everything is already done

tender perch
#

i had to comment nearly all of my code too lol

smoky narwhal
#

You don't need to do any of that

tender perch
#

so I build my 2 user objects jeffro and fred, how do i say fred.coolMethod()?

smoky narwhal
smoky narwhal
tender perch
#

because the json wasn't working for me remember

smoky narwhal
#

It's just that you changed it

tender perch
#

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

full pond
smoky narwhal
#

That's why I am asking you to fix that

#

Also Jackson can read a file itself

tender perch
#

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

smoky narwhal
#

yes

tender perch
#

I fix it, thank you

#

I never understood JSON, now I think I get why it is called OBJECT NOTATION haha

smoky narwhal
# tender perch

why do you store the json in a field and why do you have a whole method for that ?

tender perch
#

that is reading the JSON from a file as a String. IntelliJ told me to put the try/catch for it

smoky narwhal
#

and you shouldn't store the json in a field

#

also jackson can directly read a file, no need to do that

tender perch
#

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

tender perch
#

finally ready to write objects back to the the file.