1. java对象转json
Message msg = generateMessage();
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(msg);
2. json转java对象
ObjectMapper mapper = new ObjectMapper();
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
mapper.setVisibilityChecker(VisibilityChecker.Std.defaultInstance().withFieldVisibility(JsonAutoDetect.Visibility.ANY))
Message message = mapper.readValue(reqMsg.getBytes("GBK"), Message.class);
3. String与xml格式的对象互相转换
@XmlRootElement(name = "Msg")
@lombok.Data
public static String marshal(Object object, String encoding, String schemaLocation) throws JAXBException, UnsupportedEncodingException {
JAXBContext context = JAXBContext.newInstance(new Class[]{object.getClass()});
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty("jaxb.encoding", encoding);
marshaller.setProperty("jaxb.formatted.output", Boolean.valueOf(true));
if(schemaLocation != null && !"".equals(schemaLocation)) {
marshaller.setProperty("jaxb.schemaLocation", schemaLocation);
}
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
marshaller.marshal(object, outputStream);
return outputStream.toString("UTF-8");
}
public static <T> T unMarshal(Class cls, String xmlStr, String encoding) throws JAXBException {
JAXBContext context = JAXBContext.newInstance(new Class[]{cls});
Unmarshaller unMarshaller = context.createUnmarshaller();
ByteArrayInputStream inputStream = new ByteArrayInputStream(xmlStr.getBytes(Charset.forName(encoding)));
return unMarshaller.unmarshal(inputStream);
}
4.