J'ai regardé Gson de Google comme un plugin JSON potentiel. Quelqu'un peut-il me donner des conseils sur la manière de générer Java à partir de cette chaîne JSON ?
Google Gson supporte les génériques et les beans imbriqués. Le site []
en JSON représente un tableau et devrait correspondre à une collection Java telle que List
ou simplement un simple tableau Java. Le site {}
en JSON représente un objet et doit correspondre à un code Java Map
ou simplement une classe JavaBean.
Vous disposez d'un objet JSON avec plusieurs propriétés dont la propriété groups
représente un tableau d'objets imbriqués du même type. Ceci peut être analysé avec Gson de la manière suivante :
package com.stackoverflow.q1688099;
import java.util.List;
import com.google.gson.Gson;
public class Test {
public static void main(String... args) throws Exception {
String json =
"{"
+ "'title': 'Computing and Information systems',"
+ "'id' : 1,"
+ "'children' : 'true',"
+ "'groups' : [{"
+ "'title' : 'Level one CIS',"
+ "'id' : 2,"
+ "'children' : 'true',"
+ "'groups' : [{"
+ "'title' : 'Intro To Computing and Internet',"
+ "'id' : 3,"
+ "'children': 'false',"
+ "'groups':[]"
+ "}]"
+ "}]"
+ "}";
// Now do the magic.
Data data = new Gson().fromJson(json, Data.class);
// Show it.
System.out.println(data);
}
}
class Data {
private String title;
private Long id;
private Boolean children;
private List<Data> groups;
public String getTitle() { return title; }
public Long getId() { return id; }
public Boolean getChildren() { return children; }
public List<Data> getGroups() { return groups; }
public void setTitle(String title) { this.title = title; }
public void setId(Long id) { this.id = id; }
public void setChildren(Boolean children) { this.children = children; }
public void setGroups(List<Data> groups) { this.groups = groups; }
public String toString() {
return String.format("title:%s,id:%d,children:%s,groups:%s", title, id, children, groups);
}
}
C'est assez simple, n'est-ce pas ? Il suffit d'avoir un JavaBean approprié et d'appeler Gson#fromJson()
.
Voir aussi :
0 votes
Voir aussi stackoverflow.com/questions/338586/a-better-java-json-library (en anglais)
0 votes
Voici un exemple thegeekyland.blogspot.com/2015/11/