Convert JSON String to File in Java - java

I'm trying to convert an Object to JSON then convert it to File
to be able to send it to AWS S3.
Is there a way to convert the String in the most efficient way?
Thank you!
Here is my code:
String messageBody = new Gson().toJson(thisIsADtoObject);
And for the S3
PutObjectRequest request = new PutObjectRequest(s3BucketName, key, file);
amazonS3.putObject(request);

As far as I know, to create a file object to send to AWS, you will have to create the actual file on disk, e.g. with a PrintStream:
File file = new File("path/to/your/file.name");
try (PrintStream out = new PrintStream(new FileOutputStream(file))) {
out.print(messageBody);
}
Instead of using the constructor taking a file, you might want to use the one which takes an InputStream:
PutObjectRequest request = new PutObjectRequest(s3BucketName, key, inputStream, metadata);
amazonS3.putObject(request);
To convert a String to an InputStream, use
new ByteArrayInputStream(messageBody.getBytes(StandardCharsets.UTF_8));
Link to SDK JavaDoc

public class JSONStringToFile {
public static void main(String[] args) throws IOException {
JSONObject obj = new JSONObject();
obj.put("Name", "somanna");
obj.put("city", "bangalore");
JSONArray company = new JSONArray();
company.add("Compnay: mps");
company.add("Compnay: paypal");
company.add("Compnay: google");
obj.put("Company List", company);
// try-with-resources statement based on post comment below :)
try (FileWriter file = new FileWriter("/Users/<username>/Documents/file1.txt")) {
file.write(obj.toJSONString());
System.out.println("Successfully Copied JSON Object to File...");
System.out.println("\nJSON Object: " + obj);
}
}
}

It's much easier with version 2 of the AWS Java SDK.
If you have converted the object to a JSON String, using GSON or Jackson, you can upload it via:
PutObjectRequest putObjectRequest = PutObjectRequest.builder().bucket(bucket).key(s3Key).build();
s3Client.putObject(putObjectRequest, RequestBody.fromString(jsonString));
No need to set the content length manually.

Related

How to modularize the code for JsonObject and JsonArray to read Json files at class level. Which I am using later to write Testcases

I am using GSON library to read JSON file for my automation. For which I need to read file and then create a object of json while traversing the JSON.
Later I am using these objects to to modify the JSON..
I want to reduce the code for traversing down the json as many objects are getting created.
Though this works perfectly fine. Just I need to modularize the code.
Adding the code with the URL , Response and User JSON
Url.json
{"emplyee":
{"addemplyee": "<URL>/emplyee","addemplyee": "<URL>/editemplyee"}
}
Response .json
[
{"success":true},
{"success":false}
]
emplyee.json
{
"addemplyee":
{"details":{
"lst":"lastname",
"id":"username",
"Password":"password"
}
},
"editemplyee":
{ "details":{
"Password":"password"
}}}
Actual
Currently I am creating multiple objects to read ths jOSN file and later with the use of same I am updating my JSON.
Expected
Can I modularize this approach of code.
Yes you can:
public static final Gson GSON = new GsonBuilder().setPrettyPrinting().create(); //you can reuse gson as often as you like
public <T> static T readJson(String file){
try{
FileReader fr = new FileReader(new File(file)); //gson takes a filereader no need to load the string to ram
T t = GSON.fromJson(fr, T.getClass());
fr.close(); //close the reader
return t;
}catch(Error e){
//ignore or print, if you need
}
}

Modify JSON, using Java

Hello I have app that is generating JSON data. When i open the route /someData I can see the JSON as I want, but when I save it in file or print it in Eclipse it adds Object name before the data:
MyObjectSchema [latitude=45.95472, longitude=13.664836, Timezone=Europe,
currently={time=1459936800}...]
How can i delete MyObjectSchema that is before the list.
This is my code:
#Scheduled(fixedDelayString = "${fixedDelaySchema}", initialDelayString = "${initialDelaySchema}")
public MyObjectSchema createMySchema() throws IOException {
Map<String, ArrayList<MyObject>> map = new HashMap<String, ArrayList<MyObject>>();
map.put("data", (ArrayList<MyObject>) list1);
Map<String, Long> map1 = new HashMap<String, Long>();
map1.put("time", list1.get(0).getTime());
MyObjectSchema obj1 = new MyObjectSchema();
obj1.setLatitude(rf.getLatitude());
obj1.setLongitude(rf.getLongitude());
obj1.setTimezone(rf.getTimezone());
obj1.setCurrently(map1);
obj1.setHourly(map);
System.out.println(obj1);
listSchema.add(obj1);
if (list1.get(0).getTime() == 1460019600) {
String jsonString = obj1.toString();
String path = "test.json";
ObjectOutputStream outputStream = null;
try {
outputStream = new ObjectOutputStream(new FileOutputStream(path));
System.out.println("Start Writings");
outputStream.writeObject(jsonString);
outputStream.flush();
outputStream.close();
System.exit(0);
} catch (Exception e) {
System.err.println("Error: " + e);
}
}
return obj1;
}
obj1.toString() is calling the toString() method of your object MyObjectSchema which right now doesn't generate a JSON valid string. You could modify your toString() method in order to generate proper JSON by string concatenation, but I don't recommend it. Instead use a library like Jackson or Gson to easily create JSON from your objects.
I faced with similar problem in the past.
You can fix it like this:
String response = new Gson().toJson(listSchema);
BufferedWriter writer = new BufferedWriter(new FileWriter("C:\\Users\\Desktop\\file.json"));
writer.write(response);
writer.close();
Use Libraries like GSON.
To use Gson, declares the following dependency.
pom.xml
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.6.2</version>
</dependency>
// 1. Java object to JSON, and save into a file
gson.toJson(obj1, new FileWriter("D:\\test.json"));

How to retrieve the downloaded data for the offline access in android?

I have made an app and now I want to add feature of Multiple Choice Questions(near abt 2000)which will be available for offline access. What I have thought till now is to upload the text file to Google's drive and get the downloading link,Once the user downloads that text file it will be saved in Internal Storage and then fetch the required data like Questions,Options,etc.
I avoided to use SQL since it will increase my app size.Kindly Help!
Thanks in Advance!
You can use SharedPreferences for storing your question and Options. Just save the question and answer in a JSON format. While retriving you can use GSON for converting that JSON format into your Model class.
This will help you in better handling of the data.
Like this you can use :
private SharedPreferences sharedPreference;
sharedPreference=context.getApplicationContext().getSharedPreferences(FILENAME, Context.MODE_PRIVATE);
public void saveQuestionOptionResponse(String response) {
sharedPreference.edit().putString("Question", response);
sharedPreference.edit().commit();
}
public QuestionOptionModel getQuestionOption() {
Gson gson = new Gson();
String json = sharedPreference.getString("Question", "");
QuestionOptionModel model = gson.fromJson(json, QuestionOptionModel.class);
return response;
}
If you want to get the questions and options format, you should use to save the questions and options in a JSON format, put the each question and options as JSONOBJECT in a JSONARRAY. So you can retrive it easly
Then you need to fetch the downloaded file from your sdcard using the below method
//Find the directory for the SD Card using the API
//*Don't* hardcode "/sdcard"
File sdcard = Environment.getExternalStorageDirectory();
//Get the text file
File file = new File(sdcard,"file.txt");
//Read text from file
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
br.close();
}
catch (IOException e) {
//You'll need to add proper error handling here
}

json to xml java

I want convert json to xml
here is code
public class ConvertJSONtoXML {
public static void main(String[] args) throws Exception {
InputStream is = ConvertJSONtoXML.class.getResourceAsStream("demo1.txt");
String jsonData = IOUtils.toString(is);
XMLSerializer serializer = new XMLSerializer();
JSON json = JSONSerializer.toJSON(jsonData);
String xml = serializer.write((JSON) json);
System.out.println(xml);
Here is demo1.txt
{"name":"naveed" }
It reads demo1.txt file and convert into xml but i m trying to pass json as string.
String jsonString="{\"name\":\"naveed\" }";
InputStream is = ConvertJSONtoXML.class.getResourceAsStream(jsonString);
but it wont work for string..
i thing getResourceAsStream(jsonString) doesnt work for string....
please suggest any reference
The method getResourceAsStream() actually looks on the file system for resource identified by the input string and open an input stream for it.
You should rather use something like
InputStream is = new ByteArrayInputStream( jsonString.getBytes() );
Also, you should take care of using compatible charsets.

Java File URI error?

I need to get a file object online, and I know the file is located at : http://nmjava.com/Dir_App_IDs/Dir_GlassPaneDemo/GlassPaneDemo_2010_04_06_15_00_SNGRGLJAMX
If I paste it into my browser's url, I'll be able to download this file, now I'm trying to get it with Java, my code looks like this :
String File_Url="http://nmjava.com/Dir_App_IDs/Dir_GlassPaneDemo/GlassPaneDemo_2010_04_06_15_00_SNGRGLJAMX";
Object myObject=Get_Online_File(new URI(File_Url));
Object Get_Online_File(URI File_Uri) throws IOException
{
return readObject(new ObjectInputStream(new FileInputStream(new File(File_Uri))));
}
public static synchronized Object readObject(ObjectInput in) throws IOException
{
Object o;
......
return o;
}
But I got the following error message :
java.lang.IllegalArgumentException: URI scheme is not "file"
at java.io.File.<init>(File.java:366)
Why ? How to fix it ?
Frank
I'm not sure if FileInputStream is designed for reading over the internet .. try new URL(File_Uri).openConnection().getInputStream()
Don't use FileInputStream for this purpose. Create URL, then get input stream and read data from it.
URL url = new URL (fileUrl);
InputStream inputStream = url.openStream ();
readData (inputStream);
For reading data I recommend you to use Commons IO library (especially if there are 2 or more places where you work with streams, it'll save your time and make your code more expressive):
private byte[] readData (InputStream in) {
try {
return IOUtils.toByteArray (in);
} finally {
IOUtils.closeQuietly(in);
}
}
You also operate in your code with Object streams (like ObjectInputStream). But that stream should be used only to read serialized java object and it's not the case as I understand from the description (if it would be a serialized object then your browser hadn't opened that file).
I got inspired, the correct answer is :
Object myObject=Get_Online_File(new URL(File_Url));
Object Get_Online_File(URL File_Url) throws IOException
{
return readObject(new ObjectInputStream(File_Url.openConnection().getInputStream()));
// or readObject(new ObjectInputStream(File_Url.openStream()));
}
Try "file://nmjava.com/Dir_App_IDs/Dir_GlassPaneDemo/GlassPaneDemo_2010_04_06_15_00_SNGRGLJAMX"

Categories

Resources