它序列化到JSON,使用GSON庫:https://code.google.com/p/google-gson/
這裏是一個很好的教程:http://www.java2blog.com/2013/11/gson-example-read-and-write-json.html
編輯:
請重寫你的類,它解壓到一個單獨的文件,它會再滿足Java約定和封裝:
public class MyData {
private int sumaTiCuadrado;
private int n;
private int tTotal;
public MyData(int sumaTiCuadrado, int n, int tTotal) {
this.sumaTiCuadrado = sumaTiCuadrado;
this.n = n;
tTotal = tTotal;
}
public int getN() {
return n;
}
public int getSumaTiCuadrado() {
return sumaTiCuadrado;
}
public int getTTotal() {
return tTotal;
}
}
這裏是一個util類適合你:
public class JsonSerializationUtil {
private static Gson gson = new GsonBuilder().setPrettyPrinting().create();
public static void serialize(String path, Object objectToSerialize) {
String jsonString = gson.toJson(objectToSerialize);
BufferedWriter bufferedWriter = null;
try {
bufferedWriter = new BufferedWriter(new FileWriter(path));
bufferedWriter.write(jsonString);
bufferedWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static Map<Integer, MyData> deserialize(String path) {
BufferedReader bufferedReader = null;
Map<Integer, MyData> result = null;
String line = "";
StringBuilder completeStringFromFile = new StringBuilder();
try {
bufferedReader = new BufferedReader(new FileReader(path));
while ((line = bufferedReader.readLine()) != null) {
completeStringFromFile.append(line);
}
bufferedReader.close();
Type type = new TypeToken<Map<Integer, MyData>>() {
}.getType();
result = gson.fromJson(completeStringFromFile.toString(), type);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
}
和示例:
public static void main(String[] args) {
Map<Integer, MyData> map = new HashMap<Integer, MyData>();
map.put(1, new MyData(1, 1, 1));
map.put(2, new MyData(2, 2, 2));
serialize("myMap.json", map);
Map<Integer, MyData> newMap = deserialize("myMap.json");
for (Map.Entry<Integer, MyData> mapEntry : newMap.entrySet()) {
System.out.println(mapEntry.getKey() + " " + mapEntry.getValue().getN());
}
}
什麼'myFutureMap'的價值?你能舉一個例子嗎?更容易找到如何將其轉換爲所需的'HashMap'的方法。謝謝:) – QueryLars
他使用'Map.toString()',所以格式在[AbstractMap'的JavaDocs]中描述(http://docs.oracle.com/javase/7/docs/api/java/ UTIL/AbstractMap.html#的toString())。 –
@MickMnemonic,但只解釋了'{key = value,key = value}'結構,我們仍然不知道'MyData'是否有'toString'方法和它產生的輸出。我們也不知道是否有'value'部分代表內部結構如內部結構'{foo = bar}',或列出'[foo,bar]'的情況。 – Pshemo