In: Computer Science
Java
1. public void writeJSON(PrintStream ps) {
Write the member variables in JSON format to the given PrintStream
}
2. public void writeJSON(PrintStream ps){
Write the member variables in JSON format to the given PrintStream.
}
Here I have created a dummy JSON string to write it is a proper json format.
You can specify a path and file name where you want to store the JSON formatted Data
package com.kontrolscan.services.impl;
import java.io.IOException;
import java.io.PrintStream;
import org.json.JSONException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class Testing {
public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
PrintStream ps = new PrintStream("/home/amity/Desktop/atesting.txt");
writeJSON(ps);
}
public static void writeJSON(PrintStream ps) throws JsonParseException, JsonMappingException, IOException {
String s = "{\"phonetype\":\"N95\",\"cat\":\"WP\"}";
try {
String formattedJSON = beautify(s);
ps.print(formattedJSON);
ps.close();
} catch (JSONException err) {
System.out.println("JSON Parsing error");
}
}
public static String beautify(String jsonAsString) throws JsonParseException, JsonMappingException, IOException {
ObjectMapper mapper = new ObjectMapper();
Object obj = mapper.readValue(jsonAsString, Object.class);
return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
}
}