2015-01-12 2 views
2

MOXy를 사용하여 JSON 문자열을 출력하는 메서드를 작성하려고합니다. 그래서 내가 원하는 것은 내가 갈 수있는 방법이 마샬링 다음 (A SAX-문서와 같은 뭔가, 또는 종류) 일반 객체에 문자열을 구문 분석하는 것입니다 생각이Unmarshal JSON MOXy를 사용하여 "Object"에 문자열

public String formatJson(String input) { ... } 

같은 방법을 가지고있다 일부 서식 지정 속성을 사용하여 JSON으로 되돌아가는 개체 (문제는 아닙니다 :-)).

문제는 JSON 문자열 입력을 읽을 때 (내가 가능한 한 일반적인 메서드를 원할 때) 비 정렬화할 클래스가 없다는 것입니다.

[편집 됨] GSON과 Jackson 예제는 MOXy만의 질문이므로 제거되었습니다.

나는이 시도 :

public static String toFormattedJson(final String jsonString) { 
    String formatted; 
    try { 
     JAXBContext jaxbContext = JAXBContextFactory.createContext(new Class[] { JAXBElement.class }, null); 
     Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); 
     unmarshaller.setProperty(MEDIA_TYPE, MediaType.APPLICATION_JSON); 
     unmarshaller.setProperty(JSON_INCLUDE_ROOT, true); 
     StringReader reader = new StringReader(jsonString); 
     Object element = unmarshaller.unmarshal(reader); // Exception is thrown here 
     formatted = toFormattedJson(element); 
    } catch (final JAXBException e) { 
     formatted = jsonString; 
    } 
    return formatted; 
} 

을하지만, 나는이 예외

javax.xml.bind.UnmarshalException 얻을 - 링크 된 예외 : [java.lang.ClassCastException가 : org.eclipse합니다. persistence.internal.oxm.record.SAXUnmarshallerHandler는 org.eclipse.persistence.internal.oxm.record.UnmarshalRecord에 캐스팅 될 수 없습니다.

그래서 임의의 JSON 문자열을 Java 객체로 읽을 수 있습니까? 특정 문자열에 대한 클래스가 있습니까? 내가

를 포맷 할 때,

private static String toFormattedJson(Object obj) { 
    String result; 
    try (StringWriter writer = new StringWriter()) { 
     final JAXBContext jaxbContext = JAXBContextFactory.createContext(new Class[] { obj.getClass() }, null); 
     final Marshaller marshaller = jaxbContext.createMarshaller(); 
     marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); 
     marshaller.setProperty(JAXBContextProperties.MEDIA_TYPE, MediaType.APPLICATION_JSON); 
     marshaller.setProperty(MarshallerProperties.JSON_REDUCE_ANY_ARRAYS, false); 
     marshaller.setProperty(MarshallerProperties.JSON_MARSHAL_EMPTY_COLLECTIONS, false); 
     marshaller.setProperty(JAXBContextProperties.JSON_WRAPPER_AS_ARRAY_NAME, false); 
     marshaller.setProperty(JAXBContextProperties.JSON_INCLUDE_ROOT, true); 
     marshaller.marshal(obj, writer); 
     writer.flush(); 
     result = writer.toString(); 
    } catch (JAXBException | IOException e) { 
     result = obj.toString(); 
    } 
    return result; 
} 

이제 아래 (마틴 보이 텍)에서 코드를 사용하여 :

업데이트 : 이는 JSON 문자열로 개체를 포맷하는 데 사용되는 방법입니다

String jsonString = "{\"p\" : [ 1, 2, 3]}"; 

내가 얻을 :

{ 
    "p" : "1" 
} 
+0

아무도 없습니까? 아이디어가 없습니까? – Asturio

답변

2

문자열을 비 마샬 타겟으로 지정할 수 있습니다.

public static void main(String[] args) { 
     System.out.println(toFormattedJson("[{\"test\":true}, \"ok\", [\"inner\",1]]")); 
} 

public static String toFormattedJson(final String jsonString) { 
    String formatted; 
    try { 
     JAXBContext jaxbContext = JAXBContextFactory.createContext(new Class[] { JAXBElement.class }, null); 
     System.out.println("jaxbContext="+jaxbContext); 
     Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); 
     unmarshaller.setProperty(JAXBContextProperties.MEDIA_TYPE, MediaType.APPLICATION_JSON); 
     unmarshaller.setProperty(JAXBContextProperties.JSON_INCLUDE_ROOT, true); 
     StringReader reader = new StringReader(jsonString); 
     Object element = unmarshaller.unmarshal(new StreamSource(reader), String.class); 
     formatted = toFormattedJsonElement(element); 
    } catch (final JAXBException e) { 
     e.printStackTrace(); 
     formatted = jsonString; 
    } 
    return formatted; 
} 

private static String toFormattedJsonElement(Object element) { 
    return "formatted: " + element; 
} 
+0

코드가 더 잘 작동합니다. 나는 여전히 올바르게 배열되지 않은 정수 배열에 몇 가지 문제가있다. JAXBConext, JAXBContextFactory 및 Unmarshaller 클래스는 어떤 패키지에 있어야합니까? javax.xml.bind 또는 org.eclipse.persistenca.jaxb? – Asturio

+1

import org.eclipse.persistence.jaxb.JAXBContextFactory; import org.eclipse.persistence.jaxb.JAXBContextProperties; import org.eclipse.persistence.oxm.MediaType; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import javax.xml.transform.stream.StreamSource; import java.io.StringReader; –

+1

다음 문자열 "{\"p \ ": [1, 2, 3}}"의 언 마샬이 버그로보고 버그를 제기했습니다. https://bugs.eclipse.org/bugs/show_bug.cgi?id=460630 . 다른 한편으로, 나는 이런 종류의 일을하는 것이 우리에게 최선의 생각이라고 생각하지 않는다. 예를 들어 JSON 처리 https://jsonp.java.net/download.html –

관련 문제