2017-10-10 17 views
0

J'essaye de convertir le contenu XML en un objet Java en utilisant JAXB sans utiliser d'annotation. Structure Mon fichier XML (CustomerDtl.xml) est mentionné ci-dessousImpossible de Unmarshall un xml en Java en utilisant JAXB sans utiliser d'annotation- Pas d'erreur mais Unmarshalling est incorrect

<?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
<basePojo> 
<customerId>C001</customerId> 
<customerList> 
    <Customer> 
     <name>Ram</name> 
     <phoneNo>123445</phoneNo> 
    </Customer> 

    <Customer> 
     <name>Tom</name> 
     <phoneNo>2332322</phoneNo> 
    </Customer> 
</customerList> 
</basePojo> 

et mes POJO sont

BasePojo.java

package pojo; 

import java.util.List; 

import pojo.Customer; 

public class BasePojo { 

    List<Customer> customerList; 
    String customerId; 

    public List<Customer> getCustomerList() { 
     return customerList; 
    } 

    public void setCustomerList(List<Customer> customerList) { 
     this.customerList = customerList; 
    } 

    public String getCustomerId() { 
     return customerId; 
    } 

    public void setCustomerId(String customerId) { 
     this.customerId = customerId; 
    } 

} 

Customer.java

package pojo; 

public class Customer { 

    private String name; 

    private String phoneNo; 

public String getName() { 
    return name; 
} 

public void setName(String name) { 
    this.name = name; 
} 

public String getPhoneNo() { 
    return phoneNo; 
} 

public void setPhoneNo(String phoneNo) { 
    this.phoneNo = phoneNo; 
} 

} 

Ci-dessous pièce mentionnée de code que j'ai écrit pour convertir le contenu XML dans Java Object

try { 

     JAXBContext jc = JAXBContext.newInstance(BasePojo.class); 
     StreamSource xml = new StreamSource("CustomerDtl.xml"); 
     Unmarshaller unmarshaller = jc.createUnmarshaller(); 
     JAXBElement<BasePojo> jaxbElementObject = unmarshaller.unmarshal(
       xml, BasePojo.class); 
     BasePojo bPojo = jaxbElementObject.getValue(); 

     System.out.println("id="+bPojo.getCustomerId()); 
     System.out.println("list size="+bPojo.getCustomerList().size()); 

     Iterator iterator = bPojo.getCustomerList().iterator(); 
     while (iterator.hasNext()) { 
      Customer studentDetails = (Customer) iterator.next(); 
      System.out.println("Print Name:" + studentDetails.getName()); 
     } 

    } catch (JAXBException e) { 
     System.out.println("Exception:" + e); 
    } 

Et à mettre ce code est

id=C001 
list size=1 
list size=[[email protected]] 
Print Customer Name:null 

Après l'exécution de ce programme, il est imprime le bon customerId, mais il imprime la mauvaise taille de la liste des clients . Bien que la taille de la liste soit 1, et que la liste contienne un objet Client, mais lorsque je parcourt la liste et que j'essaie d'obtenir une valeur de propriété différente de Client, je reçois la valeur null. Est-ce que quelqu'un peut m'expliquer ce que j'ai besoin de corriger?

En utilisant l'annotation, j'ai essayé et cela fonctionne comme prévu. Est-ce impossible sans annotation?

+0

Vous pouvez essayer d'utiliser pour (dernier client du client: pBojo.getCustomerList()) {... au lieu de votre en boucle. Je me demande si votre Iterator générique est à l'origine du problème. Si vous allez utiliser un itérateur, il devrait au moins être Iterator iterator = ... (Un IDE comme Eclipse vous donnerait un avertissement dans votre code actuel) –

+0

passons la partie itération. Pourquoi la taille de la liste est 1, une idée? – Bikku

+0

Bonne question. Quelle (s) annotation (s) exactement utilisiez-vous pour la faire fonctionner? –

Répondre

0

Dans le fichier XML, vous n'avez pas à spécifier le nom de la classe (Customer) en tant qu'enfant de votre liste (customerList), utilisez simplement le nom de la liste directement pour chaque élément.

Ainsi, changer le code XML comme ceci:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
<basePojo> 
<customerId>C001</customerId> 

<customerList> 
    <name>Ram</name> 
    <phoneNo>123445</phoneNo> 
</customerList> 

<customerList> 
    <name>Tom</name> 
    <phoneNo>2332322</phoneNo> 
</customerList> 

</basePojo> 
0

Essayez quelque chose comme ci-dessous

 

     try { 
      XMLInputFactory xif = XMLInputFactory.newFactory(); 
      StreamSource xml = new StreamSource("CustomerDtl.xml"); 
      XMLStreamReader xsr = xif.createXMLStreamReader(xml); 
      while(xsr.hasNext()) { 
       if(xsr.isStartElement() && "Customer".equals(xsr.getLocalName())) { 
        break; 
       } 
       xsr.next(); 
      } 
      JAXBContext jc = JAXBContext.newInstance(Customer.class); 
      Unmarshaller unmarshaller = jc.createUnmarshaller(); 
      Customer customer = unmarshaller.unmarshal(xsr, Customer.class).getValue(); 
      System.out.println(customer.getName()); 

     } catch (JAXBException e) { 
      System.out.println("Exception:" + e); 
     } 

0

Ici, vous allez si vous ne voulez pas d'annotation (avec XML exact que vous partagiez).

1) Enveloppez votre liste à une classe d'emballage (pour gérer customerList)

2) Maintenant, comme je l'ai demandé dans l'observation, si vous avez l'élément « Client », puis par défaut le nom « xml » reconnu sera avec petit c. Si vous ne voulez même pas annoter cela, alors manipulez-le en le lisant.

Après l'avoir dit ici est un échantillon de travail (avec runnable principal) modifier votre BasePojo

package pojo; 

import java.io.ByteArrayInputStream; 
import java.io.StringReader; 
import java.util.Iterator; 
import java.util.List; 

import javax.xml.bind.JAXBContext; 
import javax.xml.bind.JAXBElement; 
import javax.xml.bind.Unmarshaller; 
import javax.xml.stream.XMLInputFactory; 
import javax.xml.stream.XMLStreamReader; 
import javax.xml.stream.util.StreamReaderDelegate; 
import javax.xml.transform.stream.StreamSource; 

public class BasePojo { 

    String customerId; 
    CustomerList customerList; 

    public CustomerList getCustomerList() { 
     return customerList; 
    } 

    public void setCustomerList(CustomerList customerListObject) { 
     this.customerList = customerListObject; 
    } 

    public String getCustomerId() { 
     return customerId; 
    } 

    public void setCustomerId(String customerId) { 
     this.customerId = customerId; 
    } 

    public static void main(String[] args) { 
     try { 
      String customerData = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" 
        + "<basePojo>\n" 
        + "<customerId>C001</customerId>\n" 
        + "<customerList>\n" 
        + " <Customer>\n" 
        + "  <name>Ram</name>\n" 
        + "  <phoneNo>123445</phoneNo>\n" 
        + " </Customer>\n" 
        + "\n" 
        + " <Customer>\n" 
        + "  <name>Tom</name>\n" 
        + "  <phoneNo>2332322</phoneNo>\n" 
        + " </Customer>\n" 
        + "</customerList>\n" 
        + "</basePojo>"; 
      JAXBContext jc = JAXBContext.newInstance(BasePojo.class); 
      StringReader reader = new StringReader(customerData); 
      StreamSource xml = new StreamSource(reader); 
      XMLInputFactory xif = XMLInputFactory.newFactory(); 
      XMLStreamReader xsr = xif.createXMLStreamReader(new ByteArrayInputStream(customerData.getBytes("UTF-8"))); 
      xsr = new StreamReaderDelegate(xsr) { 
       @Override 
       public String getLocalName() { 
        String localName = super.getLocalName(); 

        if ("Customer".equals(localName)) { 
         return "customer"; 
        } 
        return localName; 
       } 

      }; 

      Unmarshaller unmarshaller = jc.createUnmarshaller(); 
      JAXBElement<BasePojo> jaxbElementObject = unmarshaller.unmarshal(xsr, BasePojo.class); 
      BasePojo bPojo = jaxbElementObject.getValue(); 

      System.out.println("id=" + bPojo.getCustomerId()); 
      System.out.println("list size=" + bPojo.getCustomerList().getCustomer().size()); 

      Iterator iterator = bPojo.getCustomerList().getCustomer().iterator(); 
      while (iterator.hasNext()) { 
       Customer studentDetails = (Customer) iterator.next(); 
       System.out.println("Print Name:" + studentDetails.getName()); 
      } 

     } catch (Exception e) { 
      System.out.println("Exception:" + e); 
     } 

    } 
} 

class CustomerList { 

    private List<Customer> customer; 

    public List<Customer> getCustomer() { 
     return customer; 
    } 

    public void setCustomer(List<Customer> customer) { 
     this.customer = customer; 
    } 

} 
+0

Dans mon programme, le fichier XML se trouve dans le lecteur et le programme le lit comme un fichier. – Bikku

+0

ça marche, mais comme vous l'avez fait, un peu complexe à mon avis. Mais merci pour votre aide et vos efforts. – Bikku

+0

N'est-il pas simple de changer le code pour lire à partir du fichier (où j'utilise la chaîne). J'ai utilisé la chaîne pour l'exhaustivité de l'exemple. Et je ne vois pas à quel point le code que vous avez partagé est plus complexe. Il a juste eu une seule classe d'emballage supplémentaire. Le repos est le même que votre pojo. Le code Unmarshalling sera également identique sauf pour un override. Néanmoins, s'il vous plaît partagez votre code simple qui suit toutes vos restrictions de _no annotations_, pas de changement XML etc – Optional