简体   繁体   English

使用GSON反序列化数组

[英]Deserializing arrays using GSON

So, I'm quite new to this Json world and well I'm trying to parse this Json below into a class in java using Gson, but I'm not sure if this is the correct way, because I want this to be a list of maps where the nomeArquivo would be the key in this map, can you guys help me to achive this? 因此,我对这个Json世界还很陌生,我正尝试使用Gson将下面的Json解析为java中的一个类,但是我不确定这是否正确,因为我希望这是一个正确的方法。地图列表,其中nomeArquivo将成为该地图的关键,你们可以帮助我实现这一目标吗? Or this way I posted is fine? 还是我张贴的这种方式很好?

Test class 测试班

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 class 豆类

public class FastqcJson {

    @SerializedName("name")
    private String nomeArquivo;
    @SerializedName("data")
    private HashMap<Integer, Double> mediaBaseNumeros;

....
}

Printed Objects 打印对象

FastqcJson [nomeArquivo=SRR3192396, mediaBaseNumeros={1=31.939449600540865, 2=32.05829640249262}]
FastqcJson [nomeArquivo=SRR3192397, mediaBaseNumeros={1=32.01549563582736, 2=32.13918804626231}]

Json File 杰森文件

[   [   
        {
            "color": "#5cb85c",
            "data": [
                [
                    1,
                    31.939449600540865
                ],
                [
                    2,
                    32.05829640249262
                ]               
            ],
            "name": "SRR3192396"
        },
        {
            "color": "#5cb85c",
            "data": [
                [
                    1,
                    32.01549563582736
                ],
                [
                    2,
                    32.13918804626231
                ]
            ],
            "name": "SRR3192397"
        }
    ]
]

There is no built-in way to do this since "data" is an array of arrays in its native JSON representation. 由于“数据”是以其本机JSON表示形式的数组数组,因此没有内置方法。

To do what you want to do you will need to create a wrapper type and write a custom deserializer: 要执行您想做的事情,您将需要创建一个包装器类型并编写一个自定义反序列化器:

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();
     }
}

Add this adapter during the creation of your GSON instance with GsonBuilder.registerTypeAdapter(MediaBase.class, new MediaBaseAdapter()) and the adaptor will correctly pack and unpack your datatype. 在使用GsonBuilder.registerTypeAdapter(MediaBase.class, new MediaBaseAdapter())创建GSON实例期间添加此适配器GsonBuilder.registerTypeAdapter(MediaBase.class, new MediaBaseAdapter())然后适配器将正确打包GsonBuilder.registerTypeAdapter(MediaBase.class, new MediaBaseAdapter())压缩数据类型。

Do note that this is written from memory and I've not been able to verify that it compiles. 请注意,这是从内存写入的,我无法验证它是否可以编译。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM