Create, Write, Edit JSON file in Android Studio - java

I would like to create a JSON file in the internal storage of the phone, to store data.
I want to be able to add objects ("configX") to the file and then read the data.
It should look something like this:
{
"config1": {
"component1": "url",
"component2": "url",
"component3": "url"
},
"config2": {
"component1": "url",
"component2": "url",
"component3": "url"
}
}
I can create a JSON file like this :
public void saveToJson(){
JSONObject json = new JSONObject();
try {
json.put("component1", "url");
json.put("component2", "url");
String jsonString = json.toString();
FileOutputStream fos = this.openFileOutput("jsonfile", Context.MODE_PRIVATE);
fos.write(jsonString.getBytes());
fos.close();
Log.d("JSON" , json.toString());
} catch (IOException | JSONException e) {
e.printStackTrace();
}
}
But how to put the components in the config object ? And how to retrieve the data ?
EDIT 1 :
https://stackoverflow.com/a/62474912/11652860
Thanks for the very detailed answer, I'm doing something wrong. I have an Activity where I put and save data to the json file:
public class Data {
private Map<String, Map<String, String>> map;
public Data() {
}
public Data(Map<String, Map<String, String>> map) {
this.map = map;
}
public Map<String, Map<String, String>> getMap() {
return map;
}
public void setMap(Map<String, Map<String, String>> map) {
this.map = map;
}
}
Map<String, String> config1 = new HashMap<>();
config1.put("component1", "url1");
config1.put("component2", "url1");
config1.put("component3", "url1");
Map<String, Map<String, String>> map = new HashMap<>();
map.put("config1", config1);
Data data = new Data(map);
Gson gson = new Gson();
String json = gson.toJson(data);
FileOutputStream fos = null;
try {
fos = webViewActivity.this.openFileOutput("jsonfile", Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
fos.write(json.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
And a fragment where I load the data :
public class Data {
private Map<String, Map<String, String>> map;
public Data() {
}
public Data(Map<String, Map<String, String>> map) {
this.map = map;
}
public Map<String, Map<String, String>> getMap() {
return map;
}
public void setMap(Map<String, Map<String, String>> map) {
this.map = map;
}
}
public void load(){
FileInputStream fis = null;
try {
fis = getContext().openFileInput("jsonfile.txt");
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String text;
while ((text = br.readLine()) != null){
sb.append(text).append("\n");
Gson gson = new Gson();
String json = gson.toJson(text);
Data data = gson.fromJson(json, Data.class);
String url = data.getMap().get("config1").get("component1");
frameTV.setText(url);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null){
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
The saving and loading parts must be wrong, but they worked for getting text out a text file
EDIT 2 :
I found the problem, I wasn't loading and saving properly :
SAVING:
String filename = "jsonfile.txt";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(json.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
LOADING :
FileInputStream fis = getContext().openFileInput("jsonfile.txt");
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader bufferedReader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
String json = sb.toString();
Gson gson = new Gson();
Data data = gson.fromJson(json, Data.class);
String priceURL = data.getMap().get("config1").get("url1");
EDIT 3 :
My problem now is that I need to create the file once and then check if the file exists, if it does I need to check if config1 exists if it doesn't I need to put config in the file.
But I can't check if config1 exists because I get : java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.Map com.a.app.ui.app.appFragment$Data.getMap()
I check if it exists by doing :
Boolean configTest = data.getMap().containsKey("config1");
if(!configTest){}
How can I create the file and check the data without getting a NullPointerException ?
Thank you for helping me !

Google's Gson library will be helpful in this case.
Add dependency for Google Gson in your radle file.
dependencies {
implementation 'com.google.code.gson:gson:2.8.6'
}
Create a class for your data container
public class Data {
private Map<String, Map<String, String>> map;
public Data() {
}
public Data(Map<String, Map<String, String>> map) {
this.map = map;
}
public Map<String, Map<String, String>> getMap() {
return map;
}
public void setMap(Map<String, Map<String, String>> map) {
this.map = map;
}
}
Add data to your class
Map<String, String> config1 = new HashMap<>();
config1.put("component1", "url1");
config1.put("component2", "url1");
config1.put("component3", "url1");
Map<String, String> config2 = new HashMap<>();
config2.put("component1", "url1");
config2.put("component2", "url1");
config2.put("component3", "url1");
Map<String, Map<String, String>> map = new HashMap<>();
map.put("config1", config1);
map.put("config2", config2);
Data data = new Data(map);
Get gson from data class
Gson gson = new Gson();
String json = gson.toJson(data);
You can now save this json in a file in a text format.
Now when reading, load the content of the text file in a String say 'jsonString'.
Deserialize the jsonString to Java Object
Data data = gson.fromJson(json, Data.class);
Access configurations
String url = data.getMap().get("config1").get("component1");
Add new configurations
Map<String, String> config3 = new HashMap<>();
config3.put("component1", "url1");
config3.put("component2", "url1");
config3.put("component3", "url1");
data.getMap().put("config3", config3);
Follow again these steps to save configs
Or You can manually edit the text file to add configs according to the predefined format.
{
"maps":{
"config2":{
"component1":"url1",
"component2":"url1",
"component3":"url1"
},
"config1":{
"component1":"url1",
"component2":"url1",
"component3":"url1"
}
}
}

This is how you create multiple Objects in a single JSON object:
//Creating first Object
JSONObject config1 = new JSONObject();
try {
json.put("component1", "url");
json.put("component2", "url");
json.put("component2", "url");
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Creating second object
JSONObject config2 = new JSONObject();
try {
json.put("component1", "url");
json.put("component2", "url");
json.put("component2", "url");
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONObject finalJSON = new JSONObject();
try {
//Adding both objects in one single object
json.put("config1", config1);
json.put("config2", config2);
String jsonString = finalJSON.toString();
FileOutputStream fos = this.openFileOutput("jsonfile", Context.MODE_PRIVATE);
fos.write(jsonString.getBytes());
fos.close();
Log.d("JSON" , json.toString());
} catch (IOException | JSONException e) {
e.printStackTrace();
}
This will give you the desired output. Also, if in case you want to make any object an array, you can use JSONArray for that.

Please consider using https://github.com/google/gson. You will be working with class instance rather than with JSONObject. Much more convenient.
Just to give you the idea of what you can do:
public class TestClass {
private final Map<String, String> config1;
private final Map<String, String> config2;
public TestClass(Map<String, String> config1, Map<String, String> config2) {
this.config1 = config1;
this.config2 = config2;
}
}
Gson gson = new GsonBuilder().setPrettyPrinting().create();
Map<String, String> config1 = new HashMap<String, String>();
config1.put("hello1.1", "world1.1");
config1.put("hello1.2", "world1.2");
Map<String, String> config2 = new HashMap<String, String>();
config2.put("hello2.1", "world2.1");
config2.put("hello2.2", "world2.2");
TestClass testClass = new TestClass(config1, config2);
Log.d("zzz", gson.toJson(testClass));
The above prints:
{
"config1": {
"hello1.1": "world1.1",
"hello1.2": "world1.2"
},
"config2": {
"hello2.1": "world2.1",
"hello2.2": "world2.2"
}
}
You can go back and force between json string and the entity itself. To edit, you only need to work with object - natural and convenient way.

Related

Incompatible Type Error in Android Project

This is an Android project. I'm completely new to Java (just started learning). As stated in the title, I'm getting an Incompatible Type Error
I've attached the respective method here :
public void init(Map map) {
this.productIds = new ArrayList();
try {
if (map.containsKey("products")) {
for (Entry<String, Object> "//Error Lies here" entry : ((HashMap) map.get("products")).entrySet()) {
InAppProduct productId = new InAppProduct();
productId.productId = ((String) entry.getKey()).toLowerCase();
HashMap<String, Object> extraValues = (HashMap) entry.getValue();
if (extraValues.containsKey(ShareConstants.MEDIA_TYPE)) {
productId.productType = (String) extraValues.get(ShareConstants.MEDIA_TYPE);
}
if (extraValues.containsKey("days")) {
productId.days = ((Integer) extraValues.get("days")).intValue();
}
this.productIds.add(productId);
}
return;
}
this.productIds = new ArrayList(ConfigurationFetcher.this.mDefaultsDelegate.getDefaultsInAppPackages());
} catch (Exception e) {
e.printStackTrace();
}
}
The Error is :
Required Object but found Entry <String, Object>
Let me know if you need additional code or any details. Thank You.
Set is a generic type. It is a container that can contain any kind of object.
In your case, it seems that your Set contains Map.Entry<String, Object> objects but since you don't specify that anywhere, Java assumes your Set contains Objects (the Java class that all other classes derive from) and produces an Incompatible Type Error.
Here's a slightly altered version of your code that should work.
public void init(Map map) {
this.productIds = new ArrayList();
try {
if (map.containsKey("products")) {
// ***** We now specify the type of object that the Set contains.
Set<Map.Entry<String, Object>> entrySet = ((HashMap) hm.get("products")).entrySet();
for (Entry<String, Object> entry : entrySet) {
InAppProduct productId = new InAppProduct();
productId.productId = ((String) entry.getKey()).toLowerCase();
HashMap<String, Object> extraValues = (HashMap) entry.getValue();
if (extraValues.containsKey(ShareConstants.MEDIA_TYPE)) {
productId.productType = (String) extraValues.get(ShareConstants.MEDIA_TYPE);
}
if (extraValues.containsKey("days")) {
productId.days = ((Integer) extraValues.get("days")).intValue();
}
this.productIds.add(productId);
}
return;
}
this.productIds = new ArrayList(ConfigurationFetcher.this.mDefaultsDelegate.getDefaultsInAppPackages());
} catch (Exception e) {
e.printStackTrace();
}
}
map.get("products")).entrySet() is a set of products, each product is a Object, not Entry <String, Object>.
This should work:
public void init(Map map) {
this.productIds = new ArrayList();
try {
if (map.containsKey("products")) {
for (Object entry : ((HashMap) map.get("products")).entrySet()) {
InAppProduct productId = new InAppProduct();
productId.productId = ((String) entry.getKey()).toLowerCase();
HashMap<String, Object> extraValues = (HashMap) entry.getValue();
if (extraValues.containsKey(ShareConstants.MEDIA_TYPE)) {
productId.productType = (String) extraValues.get(ShareConstants.MEDIA_TYPE);
}
if (extraValues.containsKey("days")) {
productId.days = ((Integer) extraValues.get("days")).intValue();
}
this.productIds.add(productId);
}
return;
}
this.productIds = new ArrayList(ConfigurationFetcher.this.mDefaultsDelegate.getDefaultsInAppPackages());
} catch (Exception e) {
e.printStackTrace();
}
}

Java - Get multiple JSON values and turn into String

How would I get all the "name" values and turn them into a String?
So for example if I'd do the following:
System.out.println(value[1]);
It would print out name1.
Here is what I have so far:
JSON:
[
{
"name":"name1"
},
{
"name":"name2",
"changedToAt":1470659096000
},
{
"name":"name3",
"changedToAt":1473435817000
}
]
Java code:
try {
String UUID = p.getUniqueId().toString();
String slimUUID = UUID.replace("-", "");
InputStream in = new URL("https://api.mojang.com/user/profiles/" + slimUUID + "/names").openStream();
String json = IOUtils.toString(in);
IOUtils.closeQuietly(in);
try {
JSONParser parser = new JSONParser();
JSONObject jsonparse = (JSONObject) parser.parse(json);
//get "name" values and turn into String
} catch (ParseException e) {
System.out.println(e.getMessage());
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
You need to iterate over array and accumulate all name values into array of Strings.
So below is working source code:
JsonArray jsonObject = new JsonParser()
.parse(json)
.getAsJsonArray();
List<String> names = new ArrayList<>();
for (JsonElement jsonElement : jsonObject) {
names.add(jsonElement.getAsJsonObject().get("name").getAsString());
}
//now you can use as you wish, by index
System.out.println(names.get(1));//returns "name2"
Using the URL from your comment and Java 8 Stream API I've built this main method:
public static void main(final String[] args) throws ParseException, MalformedURLException, IOException {
final String url = "https://api.mojang.com/user/profiles/c8570e47605948d3a3cbe3ec3a681cc0/names";
final InputStream in = new URL(url).openStream();
final String json = IOUtils.toString(in);
IOUtils.closeQuietly(in);
final JSONParser parser = new JSONParser();
final JSONArray jsonparse = (JSONArray) parser.parse(json);
System.out.println(jsonparse);
System.out.println();
final List<String> names = (ArrayList<String>) jsonparse.stream().map((obj) -> {
final JSONObject object = (JSONObject) obj;
return (String) object.getOrDefault("name", "");
}).peek(System.out::println).collect(Collectors.toList());
}
Try My library: abacus-common. All the above can be replaced with:
List<Map<String, Object>> resp = HttpClient.of("https://api.mojang.com/user/profiles/" + slimUUID + "/names").get(List.class);
List<String> names = resp.stream().map(m -> (String) (m.get("name"))).collect(Collectors.toList());
By the way, if slimUUID is equal to: UUID.randomUUID().toString().replaceAll("-", ""). It's be simplified:
List<Map<String, Object>> resp = HttpClient.of("https://api.mojang.com/user/profiles/" + N.guid()+ "/names").get(List.class);
List<String> names = resp.stream().map(m -> (String) (m.get("name"))).collect(Collectors.toList());

Gson - How do you store properties and values

How do I go about storing the values for "id" and "name" as HashMap<Integer, String> respectively?
Currently, dumping out pseudoStations gives me [{"id":0,"name":"London"}, {"id":1,"name":"Nottingham"}]. Iterating through would just give me a JsonObject for each list element.
Main Class
public static void main(String[] args) {
Gson gson = new Gson();
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("stations.json"));
StationManager sm = gson.fromJson(br, StationManager.class);
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (br != null) {
closeBufferedReader(br);
}
}
}
Station Manager Class
public class StationManager {
#SerializedName("pseudoStations")
#Expose
private List<JsonObject> pseudoStations = null;
public void setPseudoStations(List<JsonObject> pseudoStations) {
this.pseudoStations = pseudoStations;
}
}
stations.json
{
"pseudoStations":[
{
"id": 0,
"name": "London"
},
{
"id": 1,
"name": "Nottingham"
}
]
}
You can loop through the List of JSONObject from StationManager and add the data to HashMap.
public static void main(String[] args) {
Map<Integer, String> output = new HashMap<Integer, String>();
Gson gson = new Gson();
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("stations.json"));
StationManager sm = gson.fromJson(br, StationManager.class);
List<JsonObject> listOfObjs = sm.getPseudoStations();
for(JsonObject obj: listOfObjs){
output.put(obj.getInt("id"), obj.getString("name"));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (br != null) {
closeBufferedReader(br);
}
}
}

Java to JSON (w/ nested elements)

I am trying to create a JSON representation out of a this java object. I am using Jackson.
private List<Map<String, String>> Crews = new ArrayList<Map<String, String>>();
public Crew() {
Map<String, String> crew1 = new HashMap<String, String>();
crew1.put("crewId", "3");
crew1.put("crewName", "T.I.P.");
crew1.put("crewIntro", "Teamwork Is Perfect");
crew1.put("crewGenre", "bboy");
crew1.put("crewAsso", "TIP Studio");
crew1.put("crewLeaderContact", "tip.tip.com");
Crews.add( crew1 );
Map<String, String> crew2 = new HashMap<String, String>();
crew2.put("crewId", "4");
crew2.put("crewName", "Pinky Chicks");
crew2.put("crewIntro", "Best feminine males");
crew2.put("crewGenre", "Girl's hip-hop");
crew2.put("crewAsso", "JBlack Studio");
crew2.put("crewLeaderContact", "jblack#jblack.com");
Crews.add( crew2 );
}
public List<Map<String, String>> getCrews() {
return Crews;
}
public void setCrews(List<Map<String, String>> crews) {
Crews = crews;
}
public static void createCrewJSON(String filePath) {
Crew crew = new Crew();
ObjectMapper mapper = new ObjectMapper();
try {
mapper.writeValue(new File(filePath), crew.getCrews());
} catch (JsonProcessingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
System.out.println("JSON Crew File Created");
}
}
These are my result:
[
{
"crewIntro":"Teamwork Is Perfect",
"crewId":"3",
"crewGenre":"bboy","crewName":"T.I.P.",
"crewLeaderContact":"tip.tip.com",
"crewAsso":"TIP Studio"
},
{
"crewIntro":"Best feminine males",
"crewId":"4",
"crewGenre":"Girl's hip-hop",
"crewName":"Pinky Chicks",
"crewLeaderContact":"jblack#jblack.com",
"crewAsso":"JBlack Studio"
}
]
How would I change my createCrewJSON method to produce this: ?
{
"Crews": [
{
"Crew": {
"crewIntro":"Teamwork Is Perfect",
"crewId":"3",
"crewGenre":"bboy","crewName":"T.I.P.",
"crewLeaderContact":"tip.tip.com",
"crewAsso":"TIP Studio"
}
},
{
"Crew": {
"crewIntro":"Best feminine males",
"crewId":"4",
"crewGenre":"Girl's hip-hop",
"crewName":"Pinky Chicks",
"crewLeaderContact":"jblack#jblack.com",
"crewAsso":"JBlack Studio"
}
}
]
}
I've done multiple searches on Google for generating these nested structures, but I only get JSON to Java results..
create pojo something like
public class Crews{
private List<Map<String, String>> crews;
// gettes ,setters
}
create object for this class. and set crews and parse this object

Java output JSON to CSV file

I'm not too familiar with how to output files back to the client with Java. I am trying to create a CSV file to be sent back to the client and opened in Excel.
I found this tool for the server side creation. I'm not sure exactly how to use it to return the actual file though. Here is a sample of code I have used to return a txt file that I think I can use parts of the response for, but I'm not fetching a file anymore since I'm creating this CSV so I'm not sure what I can use.
In the code below my biggest question is what do I have to return with the controller and how do I accomplish that? I'm not sure what I need to be returning between that and also from the CSV writer to the controller. Any help would be appreciated.
Here's my code so far:
Controller:
#RequestMapping(value = "/web/csvexport", method = RequestMethod.POST)
protected void processCSV(HttpServletRequest request, HttpServletResponse response, #RequestBody String jsonRequest)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try {
CSVWriter csvWriter = new CSVWriter();
JsonFlattener jsonFlattener = new JsonFlattener();
String fileName = "StandardQuery";
csvWriter.writeAsCSV(jsonFlattener.parseJson(jsonRequest), fileName);
} catch (Exception e) {
System.out.println("Exception: " + e);
}
}
CVS Writer:
public class CSVWriter {
public void writeAsCSV(List<Map<String, String>> flatJson, String fileName) throws FileNotFoundException {
Set<String> headers = collectHeaders(flatJson);
String output = StringUtils.join(headers.toArray(), ",") + "\n";
for (Map<String, String> map : flatJson) {
output = output + getCommaSeperatedRow(headers, map) + "\n";
}
writeToFile(output, fileName);
}
private void writeToFile(String output, String fileName) throws FileNotFoundException {
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(fileName));
writer.write(output);
} catch (IOException e) {
e.printStackTrace();
} finally {
close(writer);
}
}
private void close(BufferedWriter writer) {
try {
if (writer != null) {
writer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
private String getCommaSeperatedRow(Set<String> headers, Map<String, String> map) {
List<String> items = new ArrayList<String>();
for (String header : headers) {
String value = map.get(header) == null ? "" : map.get(header).replace(",", "");
items.add(value);
}
return StringUtils.join(items.toArray(), ",");
}
private Set<String> collectHeaders(List<Map<String, String>> flatJson) {
Set<String> headers = new TreeSet<String>();
for (Map<String, String> map : flatJson) {
headers.addAll(map.keySet());
}
return headers;
}
}
Json Flattener:
public class JsonFlattener {
public Map<String, String> parse(JSONObject jsonObject) {
Map<String, String> flatJson = new HashMap<String, String>();
flatten(jsonObject, flatJson, "");
return flatJson;
}
public List<Map<String, String>> parse(JSONArray jsonArray) {
List<Map<String, String>> flatJson = new ArrayList<Map<String, String>>();
int length = jsonArray.length();
for (int i = 0; i < length; i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Map<String, String> stringMap = parse(jsonObject);
flatJson.add(stringMap);
}
return flatJson;
}
public List<Map<String, String>> parseJson(String json) throws Exception {
List<Map<String, String>> flatJson = null;
try {
JSONObject jsonObject = new JSONObject(json);
flatJson = new ArrayList<Map<String, String>>();
flatJson.add(parse(jsonObject));
} catch (JSONException je) {
flatJson = handleAsArray(json);
}
return flatJson;
}
private List<Map<String, String>> handleAsArray(String json) throws Exception {
List<Map<String, String>> flatJson = null;
try {
JSONArray jsonArray = new JSONArray(json);
flatJson = parse(jsonArray);
} catch (Exception e) {
throw new Exception("Json might be malformed");
}
return flatJson;
}
private void flatten(JSONArray obj, Map<String, String> flatJson, String prefix) {
int length = obj.length();
for (int i = 0; i < length; i++) {
if (obj.get(i).getClass() == JSONArray.class) {
JSONArray jsonArray = (JSONArray) obj.get(i);
if (jsonArray.length() < 1) continue;
flatten(jsonArray, flatJson, prefix + i);
} else if (obj.get(i).getClass() == JSONObject.class) {
JSONObject jsonObject = (JSONObject) obj.get(i);
flatten(jsonObject, flatJson, prefix + (i + 1));
} else {
String value = obj.getString(i);
if (value != null)
flatJson.put(prefix + (i + 1), value);
}
}
}
private void flatten(JSONObject obj, Map<String, String> flatJson, String prefix) {
Iterator iterator = obj.keys();
while (iterator.hasNext()) {
String key = iterator.next().toString();
if (obj.get(key).getClass() == JSONObject.class) {
JSONObject jsonObject = (JSONObject) obj.get(key);
flatten(jsonObject, flatJson, prefix);
} else if (obj.get(key).getClass() == JSONArray.class) {
JSONArray jsonArray = (JSONArray) obj.get(key);
if (jsonArray.length() < 1) continue;
flatten(jsonArray, flatJson, key);
} else {
String value = obj.getString(key);
if (value != null && !value.equals("null"))
flatJson.put(prefix + key, value);
}
}
}
}
Here's the service that I'm calling the controller from. I used this to return a .txt file before so I'm not sure how usable it is, but I think if I stream the file back it will handle it...:
getFile: function(jsonObj, fileName) {
var _defer = $q.defer();
$http.post("/web/csvexport/", jsonObj).success(function(data, status, headers) {
var octetStreamMime = "application/octet-stream";
// Get the headers
headers = headers();
// Get the filename from the x-filename header or default to "download.bin"
//var filename = headers["x-filename"] || "logfile.log";
var filename = fileName;
// Determine the content type from the header or default to "application/octet-stream"
var contentType = headers["content-type"] || octetStreamMime;
if(navigator.msSaveBlob)
{
// Save blob is supported, so get the blob as it's contentType and call save.
var blob = new Blob([data], { type: contentType });
navigator.msSaveBlob(blob, filename);
console.log("SaveBlob Success");
}
else
{
// Get the blob url creator
var urlCreator = window.URL || window.webkitURL || window.mozURL || window.msURL;
if(urlCreator)
{
// Try to use a download link
var link = document.createElement("a");
if("download" in link)
{
// Prepare a blob URL
var blob = new Blob([data], { type: contentType });
var url = urlCreator.createObjectURL(blob);
link.setAttribute("href", url);
// Set the download attribute (Supported in Chrome 14+ / Firefox 20+)
link.setAttribute("download", filename);
// Simulate clicking the download link
var event = document.createEvent('MouseEvents');
event.initMouseEvent('click', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
link.dispatchEvent(event);
console.log("Download link Success");
} else {
// Prepare a blob URL
// Use application/octet-stream when using window.location to force download
var blob = new Blob([data], { type: octetStreamMime });
var url = urlCreator.createObjectURL(blob);
window.location = url;
console.log("window.location Success");
}
} else {
console.log("Not supported");
}
}
Firstly, why don't use CSV mime type instead of html ?
replace
response.setContentType("text/html;charset=UTF-8");
by
response.setContentType("text/csv");
And do you know that Jackson, Java JSON API handle CSV ? see
https://github.com/FasterXML/jackson-dataformat-csv
Finaly, in the controler you need to use the printWriter from the response to write the CSV.
Dont forget, to prefer Stream or BufferedString to handle large file and have better performances.

Categories