• Java 随笔记录


    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. 

    
    


  • 相关阅读:
    自定义长时间定时器对象
    poj1326
    poj1323
    poj1218
    poj1298
    poj1276
    新年的第一场雪
    Java 语言学习总结
    假使时光能够倒转
    为了回家——春运3日战纪实
  • 原文地址:https://www.cnblogs.com/dinglulu/p/5212880.html
Copyright © 2020-2023  润新知