Java 有没有办法将任意数据结构与GSON解析器相关联?

Java 有没有办法将任意数据结构与GSON解析器相关联?,java,json,gson,Java,Json,Gson,首先,我看到了,但我没有看到我的问题的完整答案,这个问题是两年前提出的 简介: 例如,我们有一个JSON,其结构如下: { "name": "some_name", "description": "some_description", "price": 123, "location": { "latitude": 456987, "longitude": 963258 } } 我可以使用它将这个JSON自动解析到我的对象的

首先,我看到了,但我没有看到我的问题的完整答案,这个问题是两年前提出的

简介:

例如,我们有一个JSON,其结构如下:

{
    "name": "some_name",
    "description": "some_description",
    "price": 123,
    "location": {
        "latitude": 456987,
        "longitude": 963258
    }
}
我可以使用它将这个JSON自动解析到我的对象的类中

为此,我必须创建描述JSON结构的类,如下所示:

public class CustomClassDescribingJSON {

    private String name;
    private String description;
    private double price;
    private Location location;

    // Some getters and setters and other methods, fields, etc

    public class Location {
        private long latitude;
        private long longitude;

    }

}
接下来,我可以将JSON自动解析为对象:

String json; // This object was obtained earlier.
CustomClassDescribingJSON object = new Gson().fromJson(json, CustomClassDescribingJSON.class);
我有几种方法可以更改类中字段的名称(用于编写更可读的代码或遵循语言指南)。其中一项是:

public class CustomClassDescribingJSON {

    @SerializedName("name")
    private String mName;

    @SerializedName("description")
    private String mDescription;

    @SerializedName("price")
    private double mPrice;

    @SerializedName("location")
    private Location mLocation;

    // Some getters and setters and other methods, fields, etc

    public class Location {

        @SerializedName("latitude")
        private long mLatitude;

        @SerializedName("longitude")
        private long mLongitude;

    }

}
使用与上面相同的代码解析JSON:

String json; // This object was obtained earlier.
CustomClassDescribingJSON object = new Gson().fromJson(json, CustomClassDescribingJSON.class);
但我找不到改变班级结构的可能性。例如,我想使用下一个类来解析相同的JSON:

public class CustomClassDescribingJSON {

    private String mName;
    private String mDescription;
    private double mPrice;

    private long mLatitude;
    private long mLongitude;

}
问题:

  • 与标题中相同:是否有方法将任意数据结构与GSON解析器关联
  • 也许还有别的图书馆可以做我想做的事

  • 只需将JSON字符串转换为
    HashMap
    ,然后通过简单的迭代来填充任何类型的自定义结构,或者在每个自定义对象类中创建一个构造函数,如下所示来填充字段

    class CustomClassDescribingJSON {
        public CustomClassDescribingJSON(Map<String, Object> data) {
           // initialize the instance member 
        }
    }
    
    自定义GSON(反)序列化程序会有帮助吗?
    请看

    试试詹根:是的,这就是我要找的。非常灵活的决定。谢谢
    Reader reader = new BufferedReader(new FileReader(new File("resources/json12.txt")));
    Type type = new TypeToken<HashMap<String, Object>>() {}.getType();
    HashMap<String, Object> data = new Gson().fromJson(reader, type);
    
    System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(data));
    
    {
        "price": 123.0,
        "location": {
          "latitude": 456987.0,
          "longitude": 963258.0
        },
        "description": "some_description",
        "name": "some_name"
    }