286 votes

Convertir des objets Java en JSON avec Jackson

Je veux que mon JSON ressemble à ça :

{
    "information": [{
        "timestamp": "xxxx",
        "feature": "xxxx",
        "ean": 1234,
        "data": "xxxx"
    }, {
        "timestamp": "yyy",
        "feature": "yyy",
        "ean": 12345,
        "data": "yyy"
    }]
}

Le code jusqu'ici :

import java.util.List;

public class ValueData {

    private List<ValueItems> information;

    public ValueData(){

    }

    public List<ValueItems> getInformation() {
        return information;
    }

    public void setInformation(List<ValueItems> information) {
        this.information = information;
    }

    @Override
    public String toString() {
        return String.format("{information:%s}", information);
    }

}

et

public class ValueItems {

    private String timestamp;
    private String feature;
    private int ean;
    private String data;

    public ValueItems(){

    }

    public ValueItems(String timestamp, String feature, int ean, String data){
        this.timestamp = timestamp;
        this.feature = feature;
        this.ean = ean;
        this.data = data;
    }

    public String getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(String timestamp) {
        this.timestamp = timestamp;
    }

    public String getFeature() {
        return feature;
    }

    public void setFeature(String feature) {
        this.feature = feature;
    }

    public int getEan() {
        return ean;
    }

    public void setEan(int ean) {
        this.ean = ean;
    }

    public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
    }

    @Override
    public String toString() {
        return String.format("{timestamp:%s,feature:%s,ean:%s,data:%s}", timestamp, feature, ean, data);
    }
}

Il me manque juste la partie où je peux convertir l'objet Java en JSON avec Jackson :

public static void main(String[] args) {
   // CONVERT THE JAVA OBJECT TO JSON HERE
    System.out.println(json);
}

Ma question est la suivante : mes classes sont-elles correctes ? Quelle instance dois-je appeler et comment puis-je obtenir cette sortie JSON ?

4 votes

Le tutoriel suivant pourrait vous aider : mkyong.com/java/how-to-convert-java-object-to-from-json-jackson

11voto

Ven Ren Points 217

Vous pouvez utiliser Google Gson comme suit

UserEntity user = new UserEntity();
user.setUserName("UserName");
user.setUserAge(18);

Gson gson = new Gson();
String jsonStr = gson.toJson(user);

3voto

Ean V Points 3578

Eh bien, même la réponse acceptée ne exactement produit ce que Op a demandé. Il produit la chaîne JSON mais avec " caractères échappés. Donc, bien que ce soit un peu tard, je réponds en espérant que cela aidera les gens ! Voici comment je procède :

StringWriter writer = new StringWriter();
JsonGenerator jgen = new JsonFactory().createGenerator(writer);
jgen.setCodec(new ObjectMapper());
jgen.writeObject(object);
jgen.close();
System.out.println(writer.toString());

3voto

ZhaoGang Points 510

Note : Pour que la solution la plus votée fonctionne, les attributs dans le POJO doivent être public ou avoir un public getter / setter :

Par défaut, Jackson 2 ne fonctionne qu'avec les champs qui sont soit publics, ou qui ont une méthode de récupération publique. qui a tous les champs privés ou package private échouera.

Je n'ai pas encore testé, mais je pense que cette règle s'applique également à d'autres librairies JSON comme google Gson.

0voto

public class JSONConvector {

    public static String toJSON(Object object) throws JSONException, IllegalAccessException {
        String str = "";
        Class c = object.getClass();
        JSONObject jsonObject = new JSONObject();
        for (Field field : c.getDeclaredFields()) {
            field.setAccessible(true);
            String name = field.getName();
            String value = String.valueOf(field.get(object));
            jsonObject.put(name, value);
        }
        System.out.println(jsonObject.toString());
        return jsonObject.toString();
    }

    public static String toJSON(List list ) throws JSONException, IllegalAccessException {
        JSONArray jsonArray = new JSONArray();
        for (Object i : list) {
            String jstr = toJSON(i);
            JSONObject jsonObject = new JSONObject(jstr);
            jsonArray.put(jsonArray);
        }
        return jsonArray.toString();
    }
}

1 votes

Trop de travail, trop de réflexion ! Les mappeurs sont censés vous libérer de ces tâches répétitives !

3 votes

J'adore les convecteurs !

Prograide.com

Prograide est une communauté de développeurs qui cherche à élargir la connaissance de la programmation au-delà de l'anglais.
Pour cela nous avons les plus grands doutes résolus en français et vous pouvez aussi poser vos propres questions ou résoudre celles des autres.

Powered by:

X