gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:24:25 26 4
gpt4 key购买 nike

首先我看过 this question ,但我没有看到我的问题的完整答案,这个问题是 2 年前提出的。

简介:

例如,我们有一个具有这种结构的 JSON:

{
"name": "some_name",
"description": "some_description",
"price": 123,
"location": {
"latitude": 456987,
"longitude": 963258
}
}

我可以使用 GSON library 将此 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);

我有几种方法可以更改我的类(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;

}

问题:

  1. 与标题相同:有没有办法将任意数据结构与 GSON 解析器相关联?
  2. 也许还有其他图书馆可以做我想做的事?

最佳答案

关于java - 有没有办法将任意数据结构与 GSON 解析器相关联?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23950549/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com