我目前正在尝试使用GoogleGson序列化并正确地反序列化一个包含元组列表的对象。我在这里发现了类似的问题here和here,但我无法调整他们的解决方案来解决我的问题,因为我的列表在一个对象中。
这里有一个简单的例子:
import com.google.gson.*;
import java.util.*;
public class SerializeTheCity {
public static void main(String[] args) {
HashMap <String, Integer> cityMap = new HashMap <>();
cityMap.put("Street A", 4);
cityMap.put("Street B", 3);
cityMap.put("Street C", 7);
cityMap.put("Street D", 8);
cityMap.put("Street E", 9);
City someCity = new City();
someCity.streets= new ArrayList<>();
someCity.streets.addAll(cityMap.entrySet());
System.out.println(someCity.streets.get(1).getValue()); //works fine, how do I serialize it?
Gson gson = new Gson();
String saveCity = gson.toJson(someCity);
System.out.println(saveCity); //does not work (empty List)
// here I tried to use a solution [link 1] that worked for a similar question.
Gson gson2 = new Gson();
JsonElement jsonTree = gson2.toJsonTree(cityMap, Map.class);
JsonObject jsonObject = new JsonObject();
jsonObject.add("city", jsonTree);
System.out.println("city = "+jsonObject); //how do I deserialize this into an object of city?
City thisCity = gson.fromJson(jsonObject, City.class);
System.out.println("streets = "+thisCity.streets); // doesnt work
//works like in [link 1]. But its not a city-object.
HashMap <String, Integer> thisStreets = gson.fromJson(jsonObject.get("city"), HashMap.class);
System.out.println("this streets = "+thisStreets);
System.out.println("is this street A?"+thisStreets.get("Street A"));
// this works, but I would like having the streets
//in a city object (I could build a new city object like "newCity.streets=thisStreets",
//but perhaps you know a smarter solution)
}
}
class City {
List<Map.Entry<String,Integer>> streets; //Street, HouseNumber
}
谢谢你的帮助。
2条答案
按热度按时间zte4gxcn1#
当您重新排列
streets
所包含的类型时,您只是混淆了GSON。您创建了一个HashMap,但随后将streets作为Map.Entry输入。如果您简单地输入
streets
作为HashMap(它的原生类型),那么一切都会正常工作。两个变化:
1.使用
List.of(cityMap);
设置带有HashMap列表streets
1.将
streets
的声明更改为List<HashMap<String,Integer>> streets;
这两个简单的更改就可以解决这个问题:
生成以下输出:
6ioyuze22#
然后你需要创建一个新的城市并设置街道。因为基本上当你反序列化时,它并不对应于你的City对象数据结构。