Domanda

Vorrei usare JAXB in un'applicazione autonoma Javase per leggere e scrivere file JSON. Sono riuscito a farlo per i file XML con il mio frammento di seguito, ma non capisco come passare a JSON:

public class Main {

  public static void main(String[] args) throws Exception {
    Book book = new Book();
    book.title = "hello";

    JAXBContext context = JAXBContext.newInstance(Book.class);
    Marshaller marshaller = context.createMarshaller();
    marshaller.marshal(book, System.out);
  }

}

Appunti:

  • Le prestazioni non sono un problema.
  • Servizi Web / REST è fuori tema.
È stato utile?

Soluzione

Usando Eclipselink Moxy, è possibile aggiungere proprietà per manipolare l'output.

    public class Main {

    public static void main(String[] args) {
        Book book = new Book();
        book.title = "hello";

        JAXBContext context;
        try {
            context = JAXBContextFactory.createContext(new Class[] {Book.class}, null);
            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(MarshallerProperties.MEDIA_TYPE, "application/json");
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            marshaller.marshal(book, System.out);
        } catch (JAXBException e) {
            e.printStackTrace();
        }
    }

}

Si tradurrà in: {"libro": {"Titolo": "Hello"}}

Entrambi org.eclipse.persistence.moxy-2.5.1.jar e org.eclipse.persistence.core-2.5.1.jar sono necessari sul percorso di classe. Mentre giocavo con questo io stesso, mi sono imbattuto: risponde jaxb più sexy. Soprattutto Blaise Doughan risponde dove molto utile. Cercare

MarshallerProperties.MEDIA_TYPE, "application/json" 

Per altri suoi esempi.

Altri suggerimenti

Se lo desideri, puoi creare un metodo separato proprio come questo molto semplice (se hai già i libri jaxb)

la classe principale

import java.io.IOException;
import javax.xml.bind.JAXBException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

public class ConvertJson {

    public static void main(String[] args) {
        final JavaObject javaObject = new JavaObject();
        javaObject.setName("Json");
        javaObject.setRole("Moderator");
        javaObject.setAge(28);

        try {
            pojo2Json(javaObject);
        } catch (JAXBException | IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    private static String pojo2Json(Object obj) throws JAXBException,
            JsonParseException, JsonMappingException, IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonString = objectMapper.writeValueAsString(obj);
        System.out.print(jsonString);
        return jsonString;
    }

Ecco il pojo

import org.codehaus.jackson.annotate.JsonProperty;
public class JavaObject{
    @JsonProperty(value = "Name")
    private String name;
    @JsonProperty(value = "Role")
    private String role;
    @JsonProperty(value = "Age")
    private int age;
    public JavaObject(){
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getRole() {
        return role;
    }
    public void setRole(String role) {
        this.role = role;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }

}

}

Lo faresti così:

public class Main {
 public static void main(String[] args) throws IOException {
  Book book = new Book();
  book.title = "hello";

  ObjectMapper mapper = new ObjectMapper();
  mapper.writeValue(System.out, book);
 }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top