我有一个 json,我在 Realm 模型中使用 gson 通过注释 @SerializedName 进行转换。
但有时在 json 中,有一个未知的键,我想将其序列化为字符串。
public class example extend Realmobject{
@SerializedName("example1")
@Expose
private String exampleNr1;
@SerializedName("example2")
@Expose
private String exampleNr2;
private String someOtherValue;
Getter / Setter here...
}
Json是这样的
[
{
"example1": "1234",
"example2": "1234",
"x": "dynamic"}, {
"example1": "1454",
"example2": "165456",
"xy": "dynamic"}]
现在我将把 x 和 xy 键(有时命名为 xyz 等)序列化为 someOtherValue 字符串。 在@SerializedName(value="",alternate={""})上我没有机会,因为我不知道该字段的名称。
我把这个连载了一遍 列表 woList = gson.fromJson(parentArray, 新的 TypeToken>() {}.getType());
最佳答案
您可以先将其转换为 JSONObject。然后您可以循环遍历 JSONObject 内的键集。
JSONObject json = gson.fromJson(stringJson, JSONObject.class);
Iterator<String> set = json.keys();
while(set.hasNext()) {
String dynamicAttributeName = set.next();
}
json.get(dynamicAttributeName); //to get the value
关于java - 如何使用动态 SerializedName 注释?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56023862/