2016-12-07 1 views
1

Est-il possible d'analyser avec snakeyaml le contenu suivant et d'obtenir un List<Radio> (où Radio est le haricot java approprié)?Parse liste de beans avec snakeyaml

- 
    id: chaine416 
    name: 'France Inter' 
    type: music 
- 
    id: chaine417 
    name: 'France Culture' 
    type: music 
- 
    id: chaine418 
    name: 'Couleur 3' 
    type: music 

new Yaml().load(...); retourne un List<HashMap>, mais j'aimerais obtenir un List<Radio> à la place.

Répondre

1

La seule façon que je sais est d'utiliser un objet supérieur pour gérer la collection.

fichier YAML:

--- 
stations: 
- 
    id: chaine416 
    name: "France Inter" 
    type: music 
- 
    id: chaine417 
    name: "France Culture" 
    type: music 
- 
    id: chaine418 
    name: "Couleur 3" 
    type: music 

Je viens d'ajouter "---", nouveau document et un attribut stations.

Puis:

package snakeyaml; 

import java.util.ArrayList; 

public class Radios { 

    ArrayList<RadioStation> stations = new ArrayList<RadioStation>(); 

    public ArrayList<RadioStation> getStations() { 
     return stations; 
    } 

    public void setStations(ArrayList<RadioStation> stations) { 
     this.stations = stations; 
    } 
} 

La RadioStation classe:

package snakeyaml; 


public class RadioStation { 
    String id; 
    String name; 
    String type; 


    public RadioStation(){ 

    } 


    public String getId() { 
     return id; 
    } 

    public void setId(String id) { 
     this.id = id; 
    } 

    public String getName() { 
     return name; 
    } 

    public void setName(String name) { 
     this.name = name; 
    } 

    public String getType() { 
     return type; 
    } 

    public void setType(String type) { 
     this.type = type; 
    } 


    @Override 
    public String toString() { 
     return "RadioStation{" + 
       "id='" + id + '\'' + 
       ", name='" + name + '\'' + 
       ", type='" + type + '\'' + 
       '}'; 
    } 
} 

Et pour lire le fichier YAML:

package snakeyaml; 

import org.yaml.snakeyaml.Yaml; 
import org.yaml.snakeyaml.constructor.Constructor; 

import java.io.FileInputStream; 
import java.io.FileNotFoundException; 


public class Test { 

    public static void main(String[] args) { 
     Yaml yaml = new Yaml(new Constructor(Radios.class)); 
     try { 
      Radios result = (Radios) yaml.load(new FileInputStream("/home/ofe/dev/projets/projets_non_byo/TachesInfoengine/src/snakeyaml/data.yaml")); 
      for (RadioStation radioStation : result.getStations()) { 
       System.out.println("radioStation = " + radioStation); 
      } 
     } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
     } 

    } 
} 
+0

Cela exige de changer le format YAML, que je ne peux pas vraiment faire, car il est fourni par un service Web tiers. – fiddler

+1

Eh bien, vous avez juste besoin d'insérer 2 lignes au début: – olikaf

+1

Eh bien, ça sent comme un hack ... mais tout ce qui fonctionne :) Merci – fiddler