将字符串转换为 HashMap

Convert String to HashMap

我必须将一些信息保存到硬盘然后加载它。 为了保存信息,我这样做:myMap.toString --> 写入文件名

然后我从磁盘读取:

String myFutureMap = read filename.
HashMap<Integer, MyData> = convertFromString(myFutureMap)

class MyData{
    public int sumaTiCuadrado;
    public int n;
    public int TTotal;
}

如何将字符串转换回哈希映射?

序列化为JSON,使用GSON库:https://code.google.com/p/google-gson/

这是一个很好的教程:http://www.java2blog.com/2013/11/gson-example-read-and-write-json.html

编辑:

请重写你的class,将其解压到一个单独的文件中,然后它将满足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;
    }
}

这里有一个实用程序 class 供您使用:

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());
    }
}

使用 toString() 不是最佳选择 - 您的 toString() 实现应该生成描述嵌入元素的结构和类型的正确字符串 - 只是您必须编写所有序列化逻辑等

更好的选择是使用一些现有的序列化机制:

Java连载

private Object convertFromBytes(byte[] value) throws IOException, ClassNotFoundException {
    try (InputStream is = new ByteArrayInputStream(value);
         ObjectInputStream ois = new ObjectInputStream(is)) {
        return ois.readObject();
    }
}

private byte[] convertToBytes(Object object) throws IOException {
    try (ByteArrayOutputStream os = new ByteArrayOutputStream();
         ObjectOutputStream oos = new ObjectOutputStream(os)) {
        oos.writeObject(object);
        oos.flush();
        return os.toByteArray();
    }
}

Gson序列化

private <T> T convertFromString(String value, Class<T> type) {
    Gson gson = new Gson();
    return gson.fromJson(value, type);
}

private String convertToString(Object object) throws IOException {
    Gson gson = new Gson();
    return gson.toJson(object);
}