简体   繁体   中英

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? 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.

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.

Do note that this is written from memory and I've not been able to verify that it compiles.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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