Create a CSV file from JSON String Java - java

I am creating a stand-alone java program. I have the code to create CSV file and it works when I put it as a string variable (eg: below)
this.btnCreateFile = new JButton("Create File");
this.btnCreateFile.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
lblOutput.setText(textArea.getText());
String jsonString = "{\"infile\": [{\"field1\": 11,\"field2\": 12,\"field3\": 13},{\"field1\": 21,\"field2\": 22,\"field3\": 23},{\"field1\": 31,\"field2\": 32,\"field3\": 33}]}";
JSONObject output;
try {
output = new JSONObject(jsonString);
JSONArray docs = output.getJSONArray("infile");
File file=new File("/tmp2/fromJSON.csv");
String csv = CDL.toString(docs);
FileUtils.writeStringToFile(file, csv);
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
But, when I change the JSON string to get from a textArea, it shows 'A JSONObject text must begin with '{' at 1 [character 2 line 1]' (eg: below)
this.btnCreateFile = new JButton("Create File");
this.btnCreateFile.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
lblOutput.setText(textArea.getText());
JSONObject output;
try {
output = new JSONObject(textArea);
JSONArray docs = output.getJSONArray("infile");
File file=new File("/tmp2/fromJSON.csv");
String csv = CDL.toString(docs);
FileUtils.writeStringToFile(file, csv);
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Does anyone have any idea on how to fix this? Thanks
This is the JSON String:
{"infile": [{"field1": 11,"field2": 12,"field3": 13},
{"field1": 21,"field2": 22,"field3": 23},
{"field1": 31,"field2": 32,"field3": 33}]}

Try changing this line
output = new JSONObject(textArea);
into
output = new JSONObject(textArea.getText());
I also suggest to print the output of:
textArea.getText()

The text { may not getting detected. Keep the escape character for flower braces.

Related

Create JSON file with huge data

Adding backup feature on my app and i am using Realm database, i want to backup it to a json file.
i have created the function for reading the database and create a JSONobject.
While doing the JSONobject.tostring i got a outofmemory error since i have more than 200'000 records.
any other way to create the json file.
RealmResults<StoneModelR> allStones = realm.where(StoneModelR.class).sort("id", Sort.ASCENDING).findAll();
for (StoneModelR singleStone : allStones) {
try {
JSONObject jObjectStone = new JSONObject();
jObjectStone.put("stoneid", singleStone.id);
jObjectStone.put("lat", singleStone.lat);
jObjectStone.put("lng", singleStone.lon);
jObjectStone.put("userid", singleStone.userid);
jObjectStone.put("owner", singleStone.owner);
jObjectStone.put("timestamp", singleStone.timestamp);
jObjectStone.put("stonetype", singleStone.stonetype);
jObjectStone.put("remarks", singleStone.description);
jObjectStone.put("imported", singleStone.imported);
jArrayStones.put(jObjectStone);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
JSONObject stoneObj = new JSONObject();
try {
stoneObj.put("stones", jArrayStones);
} catch (JSONException e) {
e.printStackTrace();
}

How to solve Function1 (Context) in Function1 cannot be applied to ()

I have the following problems:
I would like to call a function from another class so I added this line of code
Function1 func = new Function1(); and I get an error saying
Function1 (Context) in Function1 cannot be applied to ()
Furthermore, relating to this function and its error, I intend calling the aforementioned function which takes a JSON object and a Filename as parameters and it returns a file, however, when I enter it, I get the following error
Wrong 2nd argument type, found Java.lang.String required Java.io.File
The code in question is this:
JSONObject export = jsonArray1.getJSONObject(index);
File file = func.exportToFile(export, "Export.json");
The fuction in question starts like this:
public void exportToFile(JSONObject objectToExport, File fN)
{
String output = objectToExport.toString();
file_ = fN;
if (!file_.exists()) {
try {
file_.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try{
FileOutputStream fOut = new FileOutputStream(file_);
fOut.write(output.getBytes());
fOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
N.B.: I have tried to call the function like this:
File file = func.exportToFile(export, func.file);
but I only get the error saying incompatible types
Required Java.io.file
Found Void
What have I done wrong?
this func.exportToFile(export, func.file); will not return anything since exportToFile it's a void method .
change your method to make it return file this way :
public File exportToFile(JSONObject objectToExport, File fN) {
String output = objectToExport.toString();
file_ = fN;
if (!file_.exists()) {
try {
file_.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try{
FileOutputStream fOut = new FileOutputStream(file_);
fOut.write(output.getBytes());
fOut.close();
return file_;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}

Retrieve results as single string each time a method is called in java

I want to retrieve the results of a method in a single string each time the function is called. I have a method which returns different results every time. I want to put all the results as a single string.
Tried to use append() method of java but the results are getting replaced every time as the function is called each time. but i need to retrieve the previous results as well.
my code is as follows.
public void createPanel2()
{
panel2 = new JPanel();
panel2.setLayout( new FlowLayout() );
query = new JLabel("query");
textbox =new JTextField(10);
submit = new JButton("submit");
panel2.add(query);
panel2.add(textbox);
panel2.add(submit);
submit.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
String str =textbox.getText();
String serverUrl = "http://localhost:8983/solr/collection1";
SolrServer solr = new HttpSolrServer(serverUrl);
try {
for (SolrDocument next : simpleSolrQuery(solr, str +
"")) {
prettyPrint(System.out, next);
}
} catch (SolrServerException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
initFilterAndButton();
}
SolrDocumentList simpleSolrQuery(SolrServer solr,
String query) throws SolrServerException {
SolrQuery solrQuery = new SolrQuery(query);
//SolrQuery query = new SolrQuery(searchTerm);
//query.setStart((pageNum - 1) * numItemsPerPage);
//query.setRows(numItemsPerPage);
//solrQuery.setRows(Integer.MAX_VALUE);
QueryResponse resp = solr.query(solrQuery);
//System.out.println("resp"+resp);
final SolrDocumentList hits = resp.getResults();
/*for (SolrDocument d : hits) {
for (Iterator<Map.Entry<String, Object>> i = d.iterator(); i
.hasNext();) {
Map.Entry<String, Object> e2 = i.next();
System.out.println(e2.getKey() + "\t" + e2.getValue());
}
System.out.println("------------------------");
}*/
System.out.println("hits"+resp.getElapsedTime());
System.out.println("size"+hits.size());
System.out.println("num found"+hits.getNumFound());
//String str ="hello";
//createPanel1(hits);
return hits;
}
void prettyPrint(PrintStream out, SolrDocument doc) {
List<String> sortedFieldNames =
new ArrayList<String>(doc.getFieldNames());
Collections.sort(sortedFieldNames);
out.println();
// StringBuilder contentstring=new StringBuilder();
// ArrayList<String> contents=new ArrayList<>();
for (String field : sortedFieldNames) {
if(field.equals("content")){
textarea.append(String.format("%s: %s",
field,doc.getFieldValue(field)+"\n"));
out.println(String.format("\t%s: %s",
field, doc.getFieldValue(field)));
contentsmethod(doc.getFieldValue(field).toString());
// contents.add(doc.getFieldValue(field).toString());
// System.out.println("conetnts"+contentstring);
}
}
// String test=contentstring.toString();
out.println();
}
public void contentsmethod(String fieldsvalues) {
// TODO Auto-generated method stub
StringBuilder contentstring=new StringBuilder();
contentstring.append(fieldsvalues);
try {
Desktop.getDesktop().browse(new URL(serverQuery+URLEncoder.encode(contentstring.toString())).toURI());
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
The code above is calling the prettyPrint method every time and the results of that method should be retrieved to a single string which should hold the previous called results as well.
here i want to retrieve the results of contentstring.append(fieldsvalues);
But contentstring is returning only the current results and not appending the previous results.
this is obvious because the method is called everytime. Is there any work around to retrieve the previous results along with the current ones as well.
You need to move this StringBuilder contentstring=new StringBuilder(); outside of your method. Every time your method call is made, you create a new String. This is why you only get the current value.
You can make a List outside of your method and add the resulting String in that list. Otherwhise, you can create the string outside and append the results to it without instantiating a new one at every method call.
You have to do something like this:
StringBuilder contentstring = new StringBuilder();
public void contentsmethod(String fieldsvalues) {
// TODO Auto-generated method stub
contentstring.append(fieldsvalues);
try {
Desktop.getDesktop().browse(new URL(serverQuery+URLEncoder.encode(contentstring.toString())).toURI());
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

ObjectMapper append file JSON

Trying to learn about Jackson some, so I'm writing a simple program that reads a file/creates one to store some JSON in it. From the Jackson website I figured out how to read and write from the file, but in the case of my rudimentary program, i'd like to append as well. I'm basically trying to store a list of shopping lists. There is a shopping list object which has store name, amd items for that store.
The trouble is that I cannot figure a way to append another entry to the end of the file (in JSON format). Here is what I am working with so far, you can ignore the first bit it's just a silly console scanner asking for input:
public class JacksonExample {
static ObjectMapper mapper = new ObjectMapper();
static File file = new File("C:/Users/stephen.protzman/Desktop/user.json");
static List<ShoppingList> master = new ArrayList<ShoppingList>();
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
boolean running = true;
while (running) {
System.out.println("[ 1 ] Add a new shopping list");
System.out.println("[ 2 ] View all shopping lists");
System.out.println("[ 3 ] Save all shopping lists");
int choice = Integer.parseInt(in.nextLine());
switch (choice) {
case 1:
getNewList();
case 2:
display();
case 3:
running = false;
}
}
in.close();
}
public static void getNewList() {
boolean more = true;
String store, temp;
List<String> items = new ArrayList<String>();
Scanner s = new Scanner(System.in);
System.out.println("Enter the store: ");
store = s.nextLine();
System.out.println("Enter each item [If done type 'DONE'] :");
while (more) {
temp = s.nextLine();
if (temp != null) {
if (temp.toUpperCase().equals("DONE")) {
more = false;
} else {
items.add(temp);
}
}
}
save(store, items);
s.close();
}
public static void display() {
try {
ShoppingList list = mapper.readValue(file, ShoppingList.class);
System.out.println(mapper.defaultPrettyPrintingWriter()
.writeValueAsString(list));
} catch (JsonParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void save(String store, List<String> items) {
//load in old one
try {
ShoppingList list = mapper.readValue(file, ShoppingList.class);
System.out.println(mapper.defaultPrettyPrintingWriter()
.writeValueAsString(list));
} catch (JsonParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//add to end of older list
ShoppingList tempList = new ShoppingList();
tempList.setStore(store);
tempList.setItems(items);
master.add(tempList);
try {
mapper.writeValue(file, master);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I want to keep using ObjectMapper (considering im trying to learn Jackson) I just havent found a way to append yet is all. Any ideas?
To append content, you need to use Streaming API to create JsonGenerator; and then you can give this generator to ObjectMapper to write to. So something like:
JsonGenerator g = mapper.getFactory().createGenerator(outputStream);
mapper.writeValue(g, valueToWrite);
// and more
g.close();
Below method can be used to write objects into a json file in append mode. it first reads your existing json file and adds new java objects to JSON file.
public static void appendWriteToJson() {
ObjectMapper mapper = new ObjectMapper();
try {
// Object to JSON in file
JsonDaoImpl js = new JsonDaoImpl();
URL resourceUrl = js.getClass().getResource("/data/actionbean.json");
System.out.println(resourceUrl);
File file = new File(resourceUrl.toURI());
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file, true))); // append mode file writer
mapper.writeValue(out, DummyBeanObject);
} catch (Exception e) {
e.printStackTrace();
}
}

android - how to parse json from file in SDCard

hi i want to parse my downloaded json file that stored in the SDCard directory ,
i don't know how can i do that !
im google a lot but i can only find somethings like : BuffredReader , InputFileStream , ...
please help me !
here is part of my code but it have the problem i attached in the image :
File GroupsJsonFileAdress = new File(Enviroments.getExternalStorageDirectory() + "FOLDER/G.json");
try {
ObjectInputStream groupsInJson = new ObjectInputStream(new FileInputStream(GroupsJsonFileAdress));
JSONObject jsonObject = (JSONObject)groupsInJson.readObject();
String DATABASE_VERSION = jsonObject.getString("DBVersion");
JSONArray groupsArray = jsonObject.getJSONArray("Groups");
for (int i = 0; i < groupsArray.length(); i++) {
JSONObject groupJsonObjectReader = groupsArray.getJSONObject(i);
int id= groupJsonObjectReader.getInt("Id");
String gTitle = groupJsonObjectReader.getString("title");
Group loaderG = new Group();
loaderG.GroupId = id;
loaderG.Title = gTitle;
Log.i("INFO", loaderG.Title);
groupsClasses.add(loaderG);
}
} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
and here is the error i got :
http://i.stack.imgur.com/lQ3YN.jpg
Create a model that matches your Json architecture and then parse it using GSON librarie ;)
Easiest way to do it so far for me :)

Categories

Resources