将String转换为HashMap

时间:2015-05-17 10:50:54

标签: java string serialization dictionary hashmap

我必须将一些信息保存到硬盘然后加载它。 要保存信息,请执行以下操作:myMap.toString - >写入文件名

然后我从磁盘阅读:

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

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

如何将字符串转换回hashmap?

2 个答案:

答案 0 :(得分:1)

将其序列化为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;
    }
}

这是适合您的实用工具类:

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

答案 1 :(得分:0)

使用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);
}