Conversion d'objets Java en JSON avec Jackson


Je veux que mon JSON ressemble à ceci:

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

Code jusqu'à présent:

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 comment 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: Mes cours sont-ils corrects? Quelle instance dois-je appeler et comment puis-je obtenir cette sortie JSON?

Author: Navnath Godse, 2013-04-03

6 answers

Pour convertir votre object en JSON avec Jackson:

ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json = ow.writeValueAsString(object);
 312
Author: Jean Logeart, 2013-04-03 11:31:37

Cela pourrait être utile.........

objectMapper.writeValue(new File("c:\\employee.json"), employee);

   // display to console
   Object json = objectMapper.readValue(
     objectMapper.writeValueAsString(employee), Object.class);

   System.out.println(objectMapper.writerWithDefaultPrettyPrinter()
     .writeValueAsString(json));
 13
Author: Vicky, 2017-09-26 08:46:30

Je sais que c'est vieux (et je suis nouveau sur java), mais j'ai rencontré le même problème. Et les réponses n'étaient pas aussi claires pour moi qu'un débutant... j'ai donc pensé ajouter ce que j'avais appris.

J'ai utilisé une bibliothèque tierce pour aider à l'effort: org.codehaus.jackson Tous les téléchargements pour cela peuvent être trouvésici .

Pour la fonctionnalité JSON de base, vous devez ajouter les fichiers JAR suivants aux bibliothèques de votre projet: jackson-mappeur-asl et jackson-core-asl

Choisir la version dont votre projet a besoin. (Généralement, vous pouvez aller avec la dernière version stable).

Une fois qu'ils sont importés dans les bibliothèques de votre projet, ajoutez les lignes import suivantes à votre code:

 import org.codehaus.jackson.JsonGenerationException;
 import org.codehaus.jackson.map.JsonMappingException;
 import org.codehaus.jackson.map.ObjectMapper;

Avec l'objet java défini et les valeurs assignées que vous souhaitez convertir en JSON et renvoyer dans le cadre d'un service Web RESTful

User u = new User();
u.firstName = "Sample";
u.lastName = "User";
u.email = "[email protected]";

ObjectMapper mapper = new ObjectMapper();

try {
    // convert user object to json string and return it 
    return mapper.writeValueAsString(u);
}
catch (JsonGenerationException | JsonMappingException  e) {
    // catch various errors
    e.printStackTrace();
}

, Le résultat devrait ressembler à ceci: {"firstName":"Sample","lastName":"User","email":"[email protected]"}

 13
Author: f10orf12, 2018-10-04 00:27:59

Faites simplement ceci

Gson gson = new Gson();
        return Response.ok(gson.toJson(yourClass)).build();
 5
Author: Shell Scott, 2015-05-21 15:09:36

Eh bien, même la réponse acceptée nepas exactement sortie ce que op a demandé. Il génère la chaîne JSON mais avec des caractères " échappés. Donc, bien que peut-être un peu tard, je réponds en espérant que cela aidera les gens! Voici comment je le fais:

StringWriter writer = new StringWriter();
JsonGenerator jgen = new JsonFactory().createGenerator(writer);
jgen.setCodec(new ObjectMapper());
jgen.writeObject(object);
jgen.close();
System.out.println(writer.toString());
 2
Author: Ean V, 2016-01-21 03:53:51
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
Author: Artavazd Manukyan, 2016-06-08 13:40:08