好的,我可以写一个与你的问题相似的例子..
我相信您的密钥会发生变化,因为您在问题中提出的内容与您实际想要的内容不同,因此我创建了一个 Key 类,您可以将其更改为您需要的适当类 Object得到。
Key.java
import com.google.gson.annotations.SerializedName;
public class Key {
@SerializedName("key")
private String key;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
}
数据.java
import java.util.ArrayList;
import com.google.gson.annotations.SerializedName;
public class Data {
@SerializedName("someName")
private String someKey;
@SerializedName("Key")
private Key key;
@SerializedName("keys")
private ArrayList<Key> keys;
public String getSomeKey() {
return someKey;
}
public void setSomeKey(String someKey) {
this.someKey = someKey;
}
public Key getKey() {
return key;
}
public void setKey(Key key) {
this.key = key;
}
public ArrayList<Key> getKeys() {
return keys;
}
public void setKeys(ArrayList<Key> keys) {
this.keys = keys;
}
}
你可以用下面的代码测试一下
public static void main(String[] args) {
// TODO Auto-generated method stub
Key key = new Key();
key.setKey("someNumber");
ArrayList<Key> keys = new ArrayList<>();
for (int i = 0; i < 5; i++) {
Key key2 = new Key();
key2.setKey("1"+i);
keys.add(key2);
}
Data data = new Data();
data.setKey(key);
data.setKeys(keys);
String result =(new Gson()).toJson(data);
System.out.println(result);
System.out.println("\n#######\n");
Data data2 = (new Gson()).fromJson(result, Data.class);
System.out.println(data2.getKey().getKey());
}
这只是一个示例,其中类 Data 已在 JSON 中转换,然后反序列化以填充它的对象,这应该让您了解如何读取自己的数据。
输出
{"Key":{"key":"someNumber"},"keys":[{"key":"10"},{"key":"11"},{"key":"12"},{"key":"13"},{"key":"14"}]}
#######
someNumber
10
11
12
13
14