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"
}
아무도 없습니까? 아이디어가 없습니까? – Asturio