2017-05-31 150 views
0

我需要JSON轉換成XML格式值在根標籤爪哇 - JSON轉換爲XML值的根標籤

我已經和奧登類@JsonRootName("orden")配置並添加@JsonProperty所有屬性。

實際上,我有一個實現將JSON轉換爲XML,但是在子節點中有「值」。

這是我的轉換器實現:

public static String convertJsonObjectToXml (Object obj) throws JsonProcessingException { 
     ObjectMapper mapper = new ObjectMapper(); 
     mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true); 
     mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); 
     String jsonString = mapper.writeValueAsString(obj); 
     JSONObject json = new JSONObject(jsonString); 
     String xml = XML.toString(json); 
     return xml; 
    } 

,落實的結果是這樣的:

<orden> 
       <formaOp>C</formaOp> 
       <agente>109</agente> 
       <tipo>C</tipo> 
       <precio>2.5</precio> 
       <tipoVenc>72</tipoVenc> 
       <idOrigen>156934</idOrigen> 
       <instrumento>TS</instrumento> 
       <ejecucion>SINCRONICA</ejecucion> 
       <agenteCtpte>3</agenteCtpte> 
       <comitente>0</comitente> 
       <fechaOrigen>2013-10-09T08:04:13</fechaOrigen> 
       <cantidad>10</cantidad> 
</orden> 

但我需要的XML的短,不友好或任何形式的名稱下方

<orden idOrigen="156934" fechaOrigen="2014-02-19T15:11:44.000-03:00" 
     agente="109" agenteCtpte="3" tipo="C" ejecucion="SINCRONICA" instrumento="TS" 
    cantidad="10" precio="2.5" formaOp="C" tipoVenc="72"/> 

任何想法?謝謝!

+0

你爲什麼使用兩個不同的JSON庫? ---無論如何,既然你使用Jackson'ObjectMapper'來轉換爲JSON,爲什麼不使用JAXB將對象轉換爲XML呢?這樣您就可以完全控制使用JAXB註釋的XML代。 – Andreas

+0

Thaks!我會根據您的評論提供答案 –

回答

0

根據Andreas發表的評論,我使用JAXB和我的Orden類現在是混合型(可以從JSON或XML轉換而來)。

這是對象是如何配置的:

@XmlRootElement 
public class IngresarOrden extends DatosOferta { 

    private String accion; 

    private ModoEjecucion ejecucion; 

    private String operador; 

    @XmlAttribute 
    public String getAccion() { 
     return accion; 
    } 
    public void setAccion(String accion) { 
     this.accion = accion; 
    } 
    @XmlAttribute 
    public ModoEjecucion getEjecucion() { 
     return ejecucion; 
    } 
    public void setEjecucion(ModoEjecucion ejecucion) { 
     this.ejecucion = ejecucion; 
    } 
    @XmlAttribute 
    public String getOperador() { 
     return operador; 
    } 
    public void setOperador(String operador) { 
     this.operador = operador; 
    } 

@XmlAttribute是把值根標記所需的註釋。

這是全功率變換器實現:

public static <T> String converToXml (T obj) throws CommonsException { 

     JAXBContext jaxbContext; 
     String xml = null; 
     try { 
      OutputStream os = new ByteArrayOutputStream(); 
      jaxbContext = JAXBContext.newInstance(obj.getClass()); 
      Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); 
      jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); 
      jaxbMarshaller.marshal(obj, os); 
      xml = os.toString(); 
     } catch (JAXBException e) { 
      logger.error("XML converter exception: ", e); 
      throw new CommonsException("XML converter exception: ", e); 
     } 
     return xml; 
    } 

謝謝!