Reputation: 797
I need to store a Map
converted to a JSON Object
and stored to file.
I am running out of memory as the toJSon
method of the Gson
object converts the Map
to a string. Is there anyway I can store the Map
to a file in JSON format ?
Code Sample:
/**
* Created by viraj on 4/6/2015.
*/
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.json.simple.*;
import org.json.simple.parser.JSONParser;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class HealthInspection {
private Map<String,Restaurant> restaurantMap;
public void jsonParser() throws IOException{
JSONParser parser = new JSONParser();
FileWriter file = new FileWriter(System.getProperty("user.dir")+"\\src\\restaurants.json");
try{
Object obj = parser.parse(new FileReader(System.getProperty("user.dir")+"\\src\\rows.json"));
JSONObject jsonObject = (JSONObject) obj;
JSONArray data = (JSONArray) jsonObject.get("data");
for (int size=data.size(),i=0;i<size;++i){
JSONArray temp = (JSONArray) data.get(i);
String id = (String) temp.get(8);
Restaurant value = restaurantMap.get(id);
String inspectionDate = (String) temp.get(16);
String code = (String) temp.get(18);
String violationDescription = (String) temp.get(19);
String score = (String) temp.get(21);
String grade = (String) temp.get(22);
String gradeDate = (String) temp.get(23);
String inspectionType = (String) temp.get(25);
ViolationSpec v = new ViolationSpec(inspectionDate,code,violationDescription,score,grade,gradeDate,inspectionType);
if(value==null){
String name = (String) temp.get(9);
String boro = (String) temp.get(10);
String building = (String) temp.get(11);
String street = (String) temp.get(12);
String zipcode = (String) temp.get(13);
String phone = (String) temp.get(14);
String type = (String) temp.get(15);
value = new Restaurant(id,name,boro,building,street,zipcode,phone,type,v);
}
else{
value.addViolationSpec(v);
}
restaurantMap.put(id,value);
}
Gson store = new GsonBuilder().disableHtmlEscaping().create();
String json = store.toJson(restaurantMap);
file.write(json);
}
catch (Exception e){
e.printStackTrace();
}
finally {
file.close();
}
}
public HealthInspection(){
this.restaurantMap = new HashMap<String,Restaurant>();
}
public static void main(String args[]){
HealthInspection h = new HealthInspection();
try {
h.jsonParser();
}
catch (Exception e){
e.printStackTrace();
}
}
}
Upvotes: 1
Views: 217
Reputation: 47608
Directly write the Json to the file using:
store.toJson(restaurantMap, file);
Gson.toJson
accepts an Appendable
as a second argument, and FileWriter
implements that interface.
I wonder how big your restaurantMap
can be, to run out of memory. You really must have a lot of objects. Even a few mega-bytes of String
should not trigger an OutOfMemoryError
Upvotes: 3