Saltar al contenido

Jackson convertir objeto a ejemplo de código json

Ejemplo 1: serializador java json

public class someClass {
//your lcode and logic...
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addSerializer(MyAwesomeClass.class, new MyAwesomeSerializer());
mapper.registerModule(module);

jsonNode = mapper.convertValue(myAwesomeObject, JsonNode.class);
//... your code and logic
}
 
//serializer class
public class MyAwesomeSerializer extends StdSerializer<MyAwesomeClass> {

    public MyAwesomeSerializer() {
        super(MyAwesomeClass.class);
    }

    @Override
    public void serialize(MyAwesomeClass myAwesomeClass, JsonGenerator jgen, SerializerProvider provider) throws IOException {
        ObjectMapper mapper = new ObjectMapper();

        jgen.writeStartObject();
        jgen.writeStringField("name", myAwesomeClass.getName());
        jgen.writeStringField("age", myAwesomeClass.getAge());

          jgen.writeArrayFieldStart("hobbies");
          for (Hobby hobby : myAwesomeClass.getHobbies()) {
              jgen.writeObject(mapper.convertValue(hobby, JsonNode.class));
          }
          jgen.writeEndArray();
      
        jgen.writeEndObject();
    }

}

Ejemplo 2: convertir json en object jackson

ObjectMapper objectMapper = new ObjectMapper();

String carJson =
    "{ "brand" : "Mercedes", "doors" : 5 }";

try {
    Car car = objectMapper.readValue(carJson, Car.class);

    System.out.println("car brand = " + car.getBrand());
    System.out.println("car doors = " + car.getDoors());
} catch (IOException e) {
    e.printStackTrace();
}

Ejemplo 3: objeto jackson a json

ObjectMapper objectMapper = new ObjectMapper();
Car car = new Car("yellow", "renault");
objectMapper.writeValueAsString(car);

Ejemplo 4: objeto jackson a json

val objectMapper = ObjectMapper()
val car = Car("yellow", "renault")
objectMapper.writeValueAsString(car)
¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)



Utiliza Nuestro Buscador

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *