I'm trying to write a method that takes a JSON object that is stored in a mongoDB and serves a ical/ics file to the user.
This is my code so far:
#RequestMapping(value = "/ical", method = RequestMethod.GET)
public void getIcalFile(
String json,
HttpServletResponse response) {
try {
// get your file as InputStream
InputStream is = //Input stream from JSON. HOW?
// copy it to response's OutputStream
IOUtils.copy(is, response.getOutputStream());
response.flushBuffer();
} catch (IOException ex) {
//log.info("Error writing file to output stream. Filename was '" + fileName + "'");
throw new RuntimeException("IOError writinethod that takes a JSON object and serves a ical/ics file to the user. This is my code so far:g file to output stream");
}
}
I have no idea how to take an JSON object and use it as an input stream. If there is a better way to do what I am trying to achieve, I would love a suggestion.
Related
I'm trying to make a program using json to save user registers to file, but when I try to read my json I get the error "JSON malformed". This is my code to write in json:
Gson gsonObject = new Gson();
FileWriter writerFile;
try {
writerFile = new FileWriter("users.json", true);
writerFile.write(gsonObject.toJson(writerUser));
writerFile.close();
} catch (IOException e) {
e.printStackTrace();
}
I use arrays to be easy modify the values (only take the json back to array and make my modify) but i can't reader this json file after writer, this is my reader code:
Gson gson = new Gson();
List<User> userList;
try {
BufferedReader readerUserList = new BufferedReader(new FileReader("users.json"));
userList = Arrays.asList(gson.fromJson(readerUserList, User[].class));
for (User user : userList) {
System.out.println(user.toString());
}
And after that i get "json malformed" error, where is my error?
If help you guys, inside my json file is my arrays like that:
[{"name":"james","idCode":1}][{"name":"kyle","idCode":2}][{"name":"test","idCode":3}]
I've never used Gson... but your json file has format problems, it is supposed to look like this:
[{"name":"james","idCode":1},{"name":"kyle","idCode":2},{"name":"test","idCode":3}]
The problem is not when you try to read, but when you write it.
I am new to json i want get json data from a link, here from web search i have written code
private void button1_Click(object sender, EventArgs e)
{
string url = #"http://hololens5.northeurope.cloudapp.azure.com/INTERSHOP/web/WFS/inSPIRED-inTRONICS_Business-Site/en_US/-/USD/ViewProduct-Start?SKU=1599925&CategoryName=151&CatalogID=Computers";
using (WebClient wc=new WebClient())
{
json = wc.DownloadString(url);
}
string path = #"ouptputfileJSON.json";
if (!File.Exists(path))
{
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine(json);
}
}
}
When i execute this code i'm getting output in html page. how to get in json data of select product in the link provided
Here is the rest endpoint you are looking for:
http://hololens5.northeurope.cloudapp.azure.com/INTERSHOP/rest/WFS/inSPIRED-
inTRONICS_Business-Site/-;loc=en_US;cur=USD/products/1599925
Documentation about other rest endpoints:
https://support.intershop.com/kb/index.php/Display/T27711
Because
http://hololens5.northeurope.cloudapp.azure.com/INTERSHOP/web/WFS/inSPIRED-inTRONICS_Business-Site/en_US/-/USD/ViewProduct-Start?SKU=1599925&CategoryName=151&CatalogID=Computers
Is webpage and not API endpoint so you need to find proper endpoint from where you want to get data
Once you get Proper Endpoint you can use below
Here is an example how you can use httpclient to make a request
static void Main()
{
Task t = new Task(DownloadPageAsync);
t.Start();
Console.WriteLine("Downloading page...");
Console.ReadLine();
}
static async void DownloadPageAsync()
{
// ... Endpoint
string page = "request URL";
// ... Use HttpClient.
using (HttpClient client = new HttpClient())
using (HttpResponseMessage response = await client.GetAsync(page))
using (HttpContent content = response.Content)
{
// ... Read the string.
string result = await content.ReadAsStringAsync();
Console.WriteLine(result);
}
}
I made a JSON file and the I used FileOutputStream to save it as a text file in my hard drive . Then I use FileinputStream to input the file in a separated class. I use this code to print the JSON , but how can i parse it now using JSONParser .
public static void main(String[] args) throws Exception {
FileInputStream fileInputStream = new FileInputStream("D:\\XmlToJson.txt");
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
JSONArray jsonArray = (JSONArray) objectInputStream.readObject();
ObjectInputStream is not the correct class to use here. That is to read Java objects from Java's own serialisation scheme. Has nothing to do with JSON. And why JSONParser if you don't want to parse lazy and use the parse events to build some data structure other than a JSONArray then a JsonReader is the way to go.
Slightly adapted example from the Java documentation:
public static void main(String[] args) throws Exception {
FileInputStream fileInputStream = new FileInputStream("D:\\XmlToJson.txt");
JsonReader jsonReader = Json.createReader(fileInputStream);
JsonArray array = jsonReader.readArray();
jsonReader.close();
// ...
}
I am using a Vaadin upload component and so far I have managed to upload an image to a directory, and display it in a panel component after it is successfull uploaded. What I want to do after this, is to insert it in the database aswell. What I have is a table called Show which has a name, date and an image. In the Show class I have tried to have my image as a byte array or as a Blob.
Column(name="image")
private byte[] image;
#Lob
#Column(name="image")
private Blob image;
In the upload succeded method I want to convert the file to a byte array, and so far I have tried this:
File file = new File("C:\\Users\\Cristina_PC\\Desktop\\" + event.getFilename());
byte[] bFile = new byte[(int) file.length()];
try {
FileInputStream fileInputStream = new FileInputStream(file);
fileInputStream.read(bFile);
uIP.uploadImage(bFile);
fileInputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
I tried also this:
byte[] data = Files.readAllBytes(new File("C:\\Users\\Cristina_PC\\Desktop\\" + event.getFilename()).toPath());
uIP.uploadImage(data);
uIP it is actually my uploadImagePresenter, where I tried to transform the byte array to Blob, or simply pass it to the repository as byte array
public void uploadImage(byte[] data) throws SerialException, SQLException{
//Blob blob = new javax.sql.rowset.serial.SerialBlob(data);
showRepo.updateAfterImage(show, data); // or (show, blob)
}
In my repository, in my updateAfterImage method I have:
public void updateAfterImage(Show show, byte[] data) //or Blob data
{
em.getTransaction().begin(); //em - EntityManager
show.setImage(data);
em.getTransaction().commit();
}
Either with Blob or a byte array, I can't manage to update the existing show by setting its image and update it in the database (the cell remains NULL). Also I get no error to help me figure out what is going wrong. Any help/advice would be useful. Thanks!
I have found the solution. What made it work was:
em.getTransaction().begin();
em.find(Show.class, show.getId());
show.setImage(data);
em.merge(spectacol);
em.getTransaction().commit();
in my updateAfterImage method in the show repository.
How do I send java string array to sencha touch list. I am using a servlet and gson and I get the error at the line JsonObject creation.
import com.google.gson.JsonObject;
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
String[] anArray;
anArray = new String[11]; //assign each element of array later
JsonObject myObj = new JsonObject();
PrintWriter out = response.getWriter();
for(int i = 0; i <11; i++){
myObj.addProperty(anArray[i], i);
}
out.println(myObj.toString());
out.close();
}
eg:-
The following link uses jdbc to serve it via a database.
http://www.mysamplecode.com/2012/05/sencha-touch-list-example.html
Similar to this but the data is to be taken from the array of strings.
Set your content type to application/json on line 4 -
response.setContentType("application/json");
and make sure you are sending properly formatted JSON from your servlet.