2013-11-09 2 views
1

공용 XML 서비스의 일부 XML 데이터를 Simple XML Framework가있는 Java 개체로 직렬화하려고합니다. 문제는 서비스와 다른 메소드가 다른 요소 이름으로 동일한 개념을 반환한다는 것입니다. 방법 B는여러 요소 이름으로 역 직렬화하는 간단한 xml 프레임 워크

<data><foo>foo value</foo></data> 

복귀하고 방법 C는

<data><FOO>foo value</FOO></data> 

를 반환하는 반면, 예를 들어, 방법 A 어떤 방법 있는가이

<data><Foo>foo value</Foo></data> 

같은 요소 foo는 리턴 (여러 명 주석 정도)이 XML을 동일한 클래스 및 동일한 요소로 deserialize하는 방법은 무엇입니까? 예를 들어, 세 가지 "푸"객체 (방법 당 하나)에서 동일한 "foo는"요소로 세 가지 방법의 결과를 역 직렬화 :

@Root(name="data") 
public class Foo{ 
    @Element 
    public String foo; 
    (...) 
} 

답변

2

불행하게도 당신은 필드 만 @Element 당 하나 이상의 주석을 설정할 수 없습니다 하나의 이름 (대소 문자 구분)을 지원합니다. 다른 방법으로 당신은 당신의 자신에 의해 해당 필드를 역 직렬화 할 수 있습니다 - 여기에이 작업을 수행하는 방법을 예입니다 : foo가 작성된 경우 지금

String str = "<data><foo>foo value</foo></data>"; // Foo can be written as you like 

Serializer ser = new Persister(new AnnotationStrategy()); // Setting the AnnotationStrategy is important!! 
Foo f = ser.read(Foo.class, str); 

System.out.println(f); 

는 문제가되지 않습니다

@Root(name = "data") 
@Convert(FooConverter.class) // Set the converter that's used for serializing/deserializing this class 
public class Foo 
{ 
    @Element(name = "foo") // For this solution it doesn't matter what you set here 
    public String foo; 

    // ... 


    /* 
    * The converter - Implement the serialization/deserialization here. 
    * You don't have to use an inner class here. 
    */ 
    public static class FooConverter implements Converter<Foo> 
    { 
     @Override 
     public Foo read(InputNode node) throws Exception 
     { 
      Foo f = new Foo(); 
      InputNode nextNode = node.getNext(); 

      while(nextNode != null) 
      { 
       if(nextNode.getName().equalsIgnoreCase("foo")) // Here you pick-up the node, however it's written 
       { 
        f.setFoo(nextNode.getValue()); 
       } 

       nextNode = node.getNext(); 
      } 

      return f; 
     } 


     @Override 
     public void write(OutputNode node, Foo value) throws Exception 
     { 
      // Not required in this example. 
      throw new UnsupportedOperationException("Not supported yet."); 
     } 

    } 
} 

사용 예제 foo 또는 FoO으로 - 오랫동안 foo입니다.

+0

대단히 감사합니다. 그것은 작동합니다! 한가지 더 질문 ... Foo의 다른 모든 특성을 Converter의 read 메서드를 통해 직렬화해야합니까? 아니면 어떻게 든 그 기본 직렬화로 되돌릴 수 있습니까? – mentxugle

+0

변환기 내에서 'Serializer'/ 'Persister'를 사용하여 단일 필드를 deserialize 할 수 있습니다. 예. '새로운 Persister(). read (FieldClass.class, node)'가 가능합니다. 필드 당'Converter '를 설정할 수도 있습니다! 그러나 나는 100 % 확신 할 수 없다. 당신은 하나의 필드만을 관리하는 전체 클래스에 대해 변환기를 설정할 수 없다. 귀하의 경우에는'foo' 필드에 대해서만 변환기를 설정하는 것이 가장 좋은 해결책이 될 것입니다. 그러나 이름이 상수가 아니기 때문에 조회는 올바른 이름을 가진 필드에 대해서만 변환기를 사용합니다. – ollo

+0

아마도 'Persister'의 생성자에서 설정할 수있는 클래스가 도움이 될 것입니다. 그들의 문서를 읽는 것이 좋습니다. 가능한 행동을 제공 할 수 있습니다. – ollo

관련 문제