Bonjour,

Je voulais utiliser l'API json-lib pour pouvoir extraire mes fichiers du format JSON en java. Donc je commence à tester cet API pour voir si tout marche bien en regardant sur le site : http://json-lib.sourceforge.net/index.html.

J'obtiens un problème quand je veux faire la conversion : JSONObject to JavaBean.

On me retourne cet erreur : net.sf.json.JSONException: java.lang.NoSuchMethodException: spike.Import_json$MyJavaBean.<init>().

Pourtant je ne vois rien qui cloche, je ne comprends pas. Je fais donc appel à vos expertises.

Sincèrement,


Le code que j'ai utilisé, je l'ai copié du site (http://json-lib.sourceforge.net/snippets.html).

public class Import_json {

//Doit être mis dans un fichier à part de type MyJavaBean.java
public class MyJavaBean {
private String string;
private int integer;
private double dooble;
private boolean bool;

public String getString() {
return string;
}
public void setString(String string) {
this.string = string;
}
public int getInteger() {
return integer;
}
public void setInteger(int integer) {
this.integer = integer;
}
public double getDooble() {
return dooble;
}
public void setDooble(double dooble) {
this.dooble = dooble;
}
public boolean isBool() {
return bool;
}
public void setBool(boolean bool) {
this.bool = bool;
}
}

public void lecture_docjson() throws FileNotFoundException{

MyJavaBean bean = new MyJavaBean();
bean.setString( "JSON" );
bean.setInteger( 1 );
bean.setDooble( 2.0d );
bean.setBool( true );

JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON(bean);

JsonConfig jsonConfig = new JsonConfig();
jsonConfig.setRootClass(MyJavaBean.class);

MyJavaBean bean2 = (MyJavaBean) JSONSerializer.toJava(jsonObject,jsonConfig);

assertNotNull( bean2 );
assertEquals( "JSON", bean2.getString() );
assertEquals( 1, bean2.getInteger() );
assertEquals( 2.0d, bean2.getDooble(), 0d );
assertTrue( bean2.isBool() );

}
}

Edit (1 heure après, comme quoi il suffit de réfléchir des fois ^^):

En fait il fallait juste créer un fichier .java contenant la classe MyJavaBean à part et non pas dans le code ce qui pose un problème.