所以,我对这个Json世界很陌生,而且我尝试使用Gson将这个Json解析为java中的一个类,但我不确定这是否正确因为我希望这是一张地图列表,其中nomeArquivo将成为这张地图的关键,你能帮助我实现这个吗?或者这样我发布的很好吗?
测试课
public class JsonTeste {
public static void main(String[] args) {
Gson gson = new Gson();
try (Reader reader = new FileReader("foobar.json")) {
List<FastqcJson[]> list = gson.fromJson(reader, new TypeToken<List<FastqcJson[]>>(){}.getType());
for (FastqcJson[] fastqcJsons : list) {
for (FastqcJson fastqcJson : fastqcJsons) {
System.out.println(fastqcJson);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Bean类
public class FastqcJson {
@SerializedName("name")
private String nomeArquivo;
@SerializedName("data")
private HashMap<Integer, Double> mediaBaseNumeros;
....
}
印刷品
FastqcJson [nomeArquivo=SRR3192396, mediaBaseNumeros={1=31.939449600540865, 2=32.05829640249262}]
FastqcJson [nomeArquivo=SRR3192397, mediaBaseNumeros={1=32.01549563582736, 2=32.13918804626231}]
Json文件
[ [
{
"color": "#5cb85c",
"data": [
[
1,
31.939449600540865
],
[
2,
32.05829640249262
]
],
"name": "SRR3192396"
},
{
"color": "#5cb85c",
"data": [
[
1,
32.01549563582736
],
[
2,
32.13918804626231
]
],
"name": "SRR3192397"
}
]
]
答案 0 :(得分:1)
没有内置方法可以做到这一点,因为“data”是一个以其原生JSON表示形式的数组数组。
要做你想做的事,你需要创建一个包装器类型并编写一个自定义反序列化器:
public class MediaBase {
private HashMap<Integer, Double> numeros;
public MediaBase(HashMap<Integer, Double> numeros) {
this.numeros = numeros;
}
}
public class FastqcJson {
@SerializedName("name")
private String nomeArquivo;
@SerializedName("data")
private MediaBase mediaBaseNumeros;
....
}
public class MediaBaseAdapter extends TypeAdapter<MediaBase> {
@Override
public MediaBase read(JsonReader reader) throws IOException {
if (reader.peek() == JsonToken.NULL) {
reader.nextNull();
return null;
}
HashMap<Integer, Double> output = new HashMap<>();
reader.beginArray(); //Read "data" as array
while (reader.hasNext()) {
reader.beginArray(); //Read data array
int key = reader.nextInt();
double value = reader.nextDouble();
output.put(key, value);
reader.endArray();
}
reader.endArray();
return new MediaBase(output);
}
@Override
public void write(JsonWriter writer, MediaBase value) throws IOException {
if (value == null) {
writer.nullValue();
return;
}
// Inverse of reader
HashMap<Integer, Double> output = value.numeros;
writer.beginArray();
for (Map.Entry<Integer, Double> e : output.entries()) {
writer.beginArray();
writer.value(e.getKey());
writer.value(e.getValue());
writer.endArray();
}
writer.endArray();
}
}
在使用GsonBuilder.registerTypeAdapter(MediaBase.class, new MediaBaseAdapter())
创建GSON实例期间添加此适配器,适配器将正确打包并解压缩您的数据类型。
请注意,这是从内存中写的,我无法验证它是否已编译。