Reading Local Server .json File With MobileFirst Javascript Adapter
Is there any way that I can read a .json file (located in server) from a javascript http adapter? I tried a lot of methods described in the internet but they don't seem to work bec
Solution 1:
You can read a file with Javascript as shown below.
function readFile(filename) {
var content = "";
var fileReader = new java.io.FileReader(filename);
var bufferedReader = new java.io.BufferedReader(fileReader);
var line;
while((line = bufferedReader.readLine()) != null) {
content += line;
}
bufferedReader.close();
return content;
}
function test() {
var file = 'yourfilename.json';
var fileContents;
try {
fileContents = JSON.parse(readFile(file));
} catch(ex) {
// handle error
}
return {
fileContents: fileContents
};
}
Solution 2:
For those interested in using Java.
One thing you can do is create a Javascript adapter which will use Java code. It is pretty simple to set up.
First create a Javascript adapter.
Then create a Java class under the server/lib
folder. I created the class ReadJSON.java
under the package com.sample.customcode
.
Inside the ReadJSON.java
public class ReadJSON {
public static String readJSON() throws IOException {
//Open File
File file = new File("file.txt");
BufferedReader reader = null;
try {
//Create the file reader
reader = new BufferedReader(new FileReader(file));
String text = null;
//read file
while ((text = reader.readLine()) != null) {}
} finally {
try {
//Close the stream
reader.close();
}
}
return "the text from file";
}
}
Inside your javascript adapter you can use Java methods like below:
function readJOSN() {
var JSONfromServer = com.sample.customcode.ReadJSON.readJSON();
return {
result: JSONfromServer
};
}
Hope this helps.
Post a Comment for "Reading Local Server .json File With MobileFirst Javascript Adapter"