zoukankan      html  css  js  c++  java
  • 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. 

    
    


  • 相关阅读:
    安卓系统的文件管理神器Solid Explorer(v2.2)
    地月距离竟然如此遥远
    Android在争议中逃离Linux内核的GPL约束【转】
    gearman
    PHP基础学习
    函数式编程
    有向图的实现
    无向图的实现
    百度地图API获取数据
    python队列的实现
  • 原文地址:https://www.cnblogs.com/dinglulu/p/5212880.html
Copyright © 2011-2022 走看看