改造,嵌套 JSON 对象作为集合
Retrofit, nested JSON object as collection
假设我有一个 JSON:
{
"age" : 26,
"email" : "norman@futurestud.io",
"isDeveloper" : true,
"name" : "Norman",
"userAddress" : {
"city" : "Magdeburg",
"country" : "Germany",
"houseNumber" : "42A",
"street" : "Main Street"
}
}
我正在使用 Retrofit 和 jsonschema2pojo。
对于 userAdress,它生成一个包含四个字段的 class。是否可以将 userAddress 内容存储为两个字符串的 HashMap 而不是单独的 class?
使用Gson JSON 转换器库。
创建 Java class(如果您已经创建,请使用相同的 class)。 (出于测试目的,我创建了一个名为 User
的 class)
import com.google.gson.annotations.SerializedName;
import java.util.Map;
public class User {
@SerializedName("age")
private int age;
@SerializedName("email")
private String email;
@SerializedName("isDeveloper")
private boolean isDeveloper;
@SerializedName("name")
private String name;
@SerializedName("userAddress")
private Map<String, String> userAddress;
// other member variables if any
// constructors if any
// getter and setter methods
}
如果你想手动将JSON转换成POJO,这里是上面class的示例用法。
String jsonData = "your_json_data_received_from_api";
User user = new Gson().fromJson(jsonData, User.class);
// do whatever you want to with user object
或者,如果您想使用 Retrofit 在内部将 JSON 转换为 POJO,请不要担心。 Retrofit 将在内部处理它。
但请确保您在 POJO(模型)class.
内的 @SerializedName()
注释中使用正确的 JSON key
假设我有一个 JSON:
{
"age" : 26,
"email" : "norman@futurestud.io",
"isDeveloper" : true,
"name" : "Norman",
"userAddress" : {
"city" : "Magdeburg",
"country" : "Germany",
"houseNumber" : "42A",
"street" : "Main Street"
}
}
我正在使用 Retrofit 和 jsonschema2pojo。 对于 userAdress,它生成一个包含四个字段的 class。是否可以将 userAddress 内容存储为两个字符串的 HashMap 而不是单独的 class?
使用Gson JSON 转换器库。
创建 Java class(如果您已经创建,请使用相同的 class)。 (出于测试目的,我创建了一个名为 User
的 class)
import com.google.gson.annotations.SerializedName;
import java.util.Map;
public class User {
@SerializedName("age")
private int age;
@SerializedName("email")
private String email;
@SerializedName("isDeveloper")
private boolean isDeveloper;
@SerializedName("name")
private String name;
@SerializedName("userAddress")
private Map<String, String> userAddress;
// other member variables if any
// constructors if any
// getter and setter methods
}
如果你想手动将JSON转换成POJO,这里是上面class的示例用法。
String jsonData = "your_json_data_received_from_api";
User user = new Gson().fromJson(jsonData, User.class);
// do whatever you want to with user object
或者,如果您想使用 Retrofit 在内部将 JSON 转换为 POJO,请不要担心。 Retrofit 将在内部处理它。
但请确保您在 POJO(模型)class.
内的@SerializedName()
注释中使用正确的 JSON key