How can I convert JSON file into List of objects? - java

I'm trying to do a loader for my program and the saver into json works, but the reader doesn't. I'm basically converting my list of objects, let's say ArrayList ProjectArr into json which is working, now I'm gonna close terminal and load the info into my initially blank ProjectArr list so I can add the saved data loading feature. here is my reader :
public static ArrayList<Project> MapReaderforProject() {
ObjectMapper objectMapperforProject = new ObjectMapper();
String jsonfile = "C:/Users/elmm/Desktop/DS Project/DsProject/target/test1.json";
File file = new File("C:/Users/elmm/Desktop/DS Project/DsProject/target/test1.json");
try {
ProjectArr = objectMapperforProject.readValue(jsonfile,new TypeReference<ArrayList<Project>>(){});
}
catch (JsonMappingException e) {
} catch (JsonProcessingException e) {
}
System.out.println(ProjectArr.toString());
return ProjectArr;
}
But when I call this even though the JSON file is working and has the info, it's not reading anything and just prints [], empty list basically meaning it's not reading the data from JSON back into my list. Can someone please guide me?

There is some context information missing to give you more help. For example, what is ObjectMapper? Does it come from a library (and from which one) or have you written it yourself?
But what I have recognized so far: In line 3 you create a String which contains the file name. In line 4 you create a File object with the same file name. You could use the String there which you created the line above.
In line 6 you call the readValue method on the ObjectMapper instance and pass the String created in line 3, which contains the file name. Does this method really want a String there with the file name? If this is the ObjectMapper from the Jackson library, you need to parse the JSON code as the first parameter to the readValue call, not the file name.
So it looks like after line 4 you need code to read the content of the file which you should pass to the readValue method.
Check out this short tutorial: https://www.baeldung.com/jackson-object-mapper-tutorial
hth
McPringle

Related

Add array to newly created file in Java

I'm passing an array of array to a java method and I need to add that data to a new file (which will be loaded into an s3 bucket)
How do I do this? I haven't been able to find an example of this
Also, I'm sure "object" is not the correct data type this attribute should be. Array doesn't seem to be the correct one.
Java method -
public void uploadStreamToS3Bucket(String[][] locations) {
try {
AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
.withRegion(String.valueOf(awsRegion))
.build();
String fileName = connectionRequestRepository.findStream() +".json";
String bucketName = "downloadable-cases";
File locationData = new File(?????) // Convert locations attribute to a file and load it to putObject
s3Client.putObject(new PutObjectRequest(bucketName, fileName, locationData));
} catch (AmazonServiceException ex) {
System.out.println("Error: " + ex.getMessage());
}
}
You're trying to use PutObjectRequest(String,String,File)
but you don't have a file. So you can either:
Write your object to a file and then pass that file
or
Use the PutObjectRequest(String,String,InputStream,ObjectMetadata) version instead.
The later is better as you save the intermediate step.
As for how to write an object to a stream you may ask: Check this How can I convert an Object to Inputstream
Bear in mind to read it you have to use the same format.
It might be worth to think about what kind of format you want to save your information, because it might be needed to be read for another program, or maybe by another human directly from the bucket and there might be other formats / serializers that area easy to read (if you write JSON for instance) or more efficient (if you use another serializer that takes less space).
As for the type of array of array you can use the [][] syntax. For instance an array of array of Strings would be:
String [][] arrayOfStringArrays;
I hope this helps.

Android Read/Write JSON file to Internal Storage

I'm trying to use Gson to serialize my Java classes and store them in a .json file. I have an ArrayList<Foo> that I want to store under the node labeled Foo. Gson outputs something like this:
[{'id':1},{'id':2},{'id':3}]
I want the Json file to look like this:
{
'Foo': [{'id':1},{'id':2},{'id':3}],
'bar': ...
}
I've tried using the JsonWriter class, but I believe this is for external storage since I am getting a ReadOnly error. This is how I'm trying to write it:
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(gson.toJson(foos).getBytes()); // foos is ArrayList<Foo>
fos.close();
I'm thinking I need to store it in a JsonObject instead of writing it directly to a file. And instead of Jsonifying the entire ArrayList I could append each object individually. If I do this, how would I append it into the file (as opposed to the JsonObject)?
The main issue I'm facing is actually reading from the file. How do I go about reading the entire Json file into a JsonObject?
To get your desired output format, you could put your list in a Map with the key "foo."
Map<String, List<Foo>> map = new HashMap<>();
map.put("Foo", foos);
String output = gson.toJson(map);
Then you should get this output
{
'Foo': [{'id':1},{'id':2},{'id':3}]
}
Obviously the main reason you would want to do something like this is if you were storing things other than a list called 'Foo'.

How to add append a new class object to the existing JSON file in Java?

I am trying to append a class object to the existing json file using java but getting following output:
[{"email_id":"anu55182#gmail.com","password":"Password
","user_name":"Anubhav Singh"}]
{"email_id":"madhav123#gmail.com","password":"madhav1234",
"user_name":"Madhav kumar"}
But the expected output should be:
[{"email_id":"anu55182#gmail.com", "password":"Password
","user_name":"Anubhav
Singh"},{"email_id":"madhav123#gmail.com","password":"madhav1234","user_name":"Madhav kumar"}]
My code:
FileWriter file = new FileWriter("/home/anubhav55182/NetBeansProjects/Tweetoria/src/java/Signup/data.json",Boolean.TRUE);//output json file
JSONObject obj = new JSONObject();//for json file generation
obj.put("user_name",name);
obj.put("user_id",username);
obj.put("email_id",email);
obj.put("password",pass);
file.write(obj.toJSONString());
file.flush();
Could someone help me to append new object to existing json file using java.
Thanks in advance for your help.
You're currently only adding another JSONObject to the file. The functionality you're looking for requires you to read in the existing file (with email_id: anu55182#gmail.com) as a JSONArray. From there, you can append the array with your new object.
You'll want to read in the file as an array, put the info to be added into a JSONObject (as you have above) and then add that object to the array.
Here are the Oracle docs for JSONArray: http://docs.oracle.com/javaee/7/api/javax/json/JsonArray.html

How to write CSV to JSON without a header row, using CDL

I had some data the mongodb database in JSON format...I wanto to convert it into JSON format for further processing....I converted my data into CSV format but I don't want the headings in the CSV file....I Want to remove the headings from the CSV file. Hope my question is clear now.........
My CSV file has the following format.
**date,lng,time,place**
16-05-2013,77.152515,NIGHT,LosAngeles
16-05-2013,,77.883754,EVENING,NY
-----------------------------------
------------------------------------
-------------------------------------
I converted my jsondata into CSV and tried to replace the headings date,lng,time,place but I didn't find any way to do it through coding.....Can anyone guide me....
JSONObject root = new JSONObject(data.getJsonData());
JSONArray docs = root.getJSONArray("data");
File file=new File("/home/Documents/file1.csv");
String csv = CDL.toString(docs);
System.out.println("csv"+csv);
try {
FileUtils.writeStringToFile(file,csv);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The solution is to use the toString that takes a separate array of names, passing the names like so:
String csv = CDL.toString(docs.getJSONObject(0).names(), docs);
If you want to avoid a JSONException on an empty docs array you will want to check to make sure that docs is not empty before doing the above.
For more details, take a look at the documentation forCDL, in particular CDL.toString(JSONArray, JSONArray), which states:
The list of names is not included in the output.
If you take a look at the source you can get a slightly clearer idea of what is happening.
Note that if you want to change the set of columns in the output, or their order, you can pass in any JSONArray of names you want as the first parameter - the output columns will correspond to the names in that array.

Write to Json using libGDX

I am new to Json and libGDX but I have created a simple game and I want to store player names and their scores in a Json file. Is there a way to do this? I want to create a Json file in Gdx.files.localStorage if it doesnt exist and if it does, append new data to it.
I have checked code given at :
1>Using Json.Serializable to parse Json files
2>Parsing Json in libGDX
But I failed to locate how to actually create a Json file and write multiple unique object values (name and score of each player) to it. Did I miss something from their codes?
This link mentions how to load an existing json but nothing else.
First of all i have to say that i never used the Libgdx Json API myself. But i try to help you out a bit.
I think this Tutorial on github should help you out a bit.
Basicly the Json API allows you to write a whole object to a Json object and then parse that to a String. To do that use:
PlayerScore score = new PlayerScore("Player1", 1537443); // The Highscore of the Player1
Json json = new Json();
String score = json.toJson(score);
This should then be something like:
{name: Player1, score: 1537443}
Instead of toJson() you can use prettyPrint(), which includes linebreaks and tabs.
To write this to a File use:
FileHandle file = Gdx.files.local("scores.json");
file.writeString(score, true); // True means append, false means overwrite.
You can also customize your Json by implementing Json.Serializable or by adding the values by hand, using writeValue.
Reading is similar:
FileHandle file = Gdx.files.local("scores.json");
String scores = file.readString();
Json json = new Json();
PlayerScore score = json.fromJson(PlayerScore.class, scores);
If you have been using a customized version by implementing Json.Serializable you have implemented the read (Json json, JsonValue jsonMap) method. If you implemented it correctly you the deserialization should work. If you have been adding the values by hand you need to create a JsonValuejsonFile = new JsonValue(scores). scores is the String of the File. Now you can cycle throught the childs of this JsonValue or get its childs by name.
One last thing: For highscores or things like that maybe the Libgdx Preferences are the better choice. Here you can read how to use them.
Hope i could help.

Categories

Resources