XmlMapper方法代码示例

示例1: testParseSiteMap

import com.fasterxml.jackson.dataformat.xml.XmlMapper;

@Test
public void testParseSiteMap() throws Exception {

    InputStream stream = getClass().getClassLoader().getResourceAsStream("xml/footer.xml");
    XmlMapper xmlMapper = new XmlMapper();
    Footer footer = xmlMapper.readValue(stream, Footer.class);
    assertEquals(7, footer.getMenuset().size());
    SiteMap frSiteMap = footer.getMenuset().get(0);
    assertEquals("fr", frSiteMap.getLanguage());
    assertEquals(13, frSiteMap.getEntries().size());
    assertEquals("/fr/association", frSiteMap.getEntries().get(0).getUrl());
    assertEquals("Association", frSiteMap.getEntries().get(0).getLabel());

    SiteMap enSiteMap = footer.getMenuset().get(1);
    assertEquals("en", enSiteMap.getLanguage());
    assertEquals(13, enSiteMap.getEntries().size());
}

示例2: adaptXMLLine

import com.fasterxml.jackson.dataformat.xml.XmlMapper;
private ObjectNode adaptXMLLine(String line)
{
  XmlMapper mapper = new XmlMapper();
  ObjectNode objNode = null;
  try
  {
    objNode = mapper.readValue(line, ObjectNode.class);
    objNode.put("_id", objNode.get("Id").asText());
    objNode.remove("Id");
  } catch (Exception e)
  {
    e.printStackTrace();
  }

  return objNode;
}

示例3: testParseHeaderSiteMap

import com.fasterxml.jackson.dataformat.xml.XmlMapper;

@Test
public void testParseHeaderSiteMap() throws Exception {

    InputStream stream = getClass().getClassLoader().getResourceAsStream("xml/header.xml");
    XmlMapper xmlMapper = new XmlMapper();
    HeaderMenuSet header = xmlMapper.readValue(stream, HeaderMenuSet.class);

    validateMenuSet(header);

    List<SiteMapMenuItem> siteMapMenuItems = header.getMenuset().get(0).getItems();
    assertEquals("/static/img/logo.png", siteMapMenuItems.get(0).getImgUrl());

    SiteMapMenuItem catalogMenuItem = siteMapMenuItems.get(5);
    assertEquals("https://portal.ozwillo.com/fr/store", catalogMenuItem.getUrl());
    assertEquals("/static/img/icone-catalogue-color.png", catalogMenuItem.getImgUrl());
    assertEquals("Catalogue", catalogMenuItem.getLabel());

    assertEquals(3, siteMapMenuItems.get(2).getItems().size());
    SiteMapMenuItem offerDataMenuItem = siteMapMenuItems.get(2).getItems().get(0);
    assertEquals("/fr/offre-donnees", offerDataMenuItem.getUrl());
    assertEquals("menu", offerDataMenuItem.getType());
    assertEquals("Données", offerDataMenuItem.getLabel());
}

示例4: toMetadata

import com.fasterxml.jackson.dataformat.xml.XmlMapper; 

public static Edmx toMetadata(final InputStream input) {
    try {
        final XmlMapper xmlMapper = new XmlMapper(
                new XmlFactory(new InputFactoryImpl(), new OutputFactoryImpl()), new JacksonXmlModule());
        xmlMapper.addHandler(new DeserializationProblemHandler() {

            @Override
            public boolean handleUnknownProperty(final DeserializationContext ctxt, final JsonParser jp,
                    final JsonDeserializer<?> deserializer, final Object beanOrClass, final String propertyName)
                    throws IOException, JsonProcessingException {

                // 1. special handling of AbstractAnnotatedEdm's fields
                if (beanOrClass instanceof AbstractAnnotatedEdm
                        && AbstractAnnotatedEdmUtils.isAbstractAnnotatedProperty(propertyName)) {

                    AbstractAnnotatedEdmUtils.parseAnnotatedEdm((AbstractAnnotatedEdm) beanOrClass, jp);
                } // 2. skip any other unknown property
                else {
                    ctxt.getParser().skipChildren();
                }

                return true;
            }
        });
        return xmlMapper.readValue(input, Edmx.class);
    } catch (Exception e) {
        throw new IllegalArgumentException("Could not parse as Edmx document", e);
    }
}

示例5: getManufacturingParameters

import com.fasterxml.jackson.dataformat.xml.XmlMapper; 

public List<ManufacturingParameters> getManufacturingParameters() {
  List<ManufacturingParameters> manufacturingParameters = newArrayList();
  try {
    for (DatabasePage page : getPages()) {
      ByteArrayInputStream inputStream = new ByteArrayInputStream(page.getPageData());
      DataInput input = this.dataInputFactory.create(inputStream);
      // TODO: something better than ignoring the data?
      long systemSeconds = UnsignedInts.toLong(input.readInt());
      long displaySeconds = UnsignedInts.toLong(input.readInt());

      byte[] xmlBytes = new byte[inputStream.available() - 2];
      input.readFully(xmlBytes);

      validateCrc(input.readUnsignedShort(), page.getPageData());

      XmlMapper xmlMapper = new XmlMapper();
      ManufacturingParameters parameterPage = xmlMapper.readValue(new String(xmlBytes, "UTF-8"),
              ManufacturingParameters.class);
      manufacturingParameters.add(parameterPage);
    }
    return manufacturingParameters;
  } catch (IOException e) {
    throw Throwables.propagate(e);
  }
}

示例6: unmarshal

import com.fasterxml.jackson.dataformat.xml.XmlMapper; 

@Test
public void unmarshal() throws Exception {
    XmlMapper serializer = new XmlMapper();

    ToolSuiteXml toolSuiteXml = serializer.readValue(responseXml, ToolSuiteXml.class);

    assertThat(toolSuiteXml.getReleases(), notNullValue());
    assertThat(toolSuiteXml.getReleases().size(), equalTo(4));
    Release release = toolSuiteXml.getReleases().get(0);
    assertThat(release.getDownloads().size(), equalTo(7));
    assertThat(release.getWhatsnew(), notNullValue());

    assertThat(toolSuiteXml.getOthers(), notNullValue());
    assertThat(toolSuiteXml.getOthers().size(), equalTo(43));
    Release oldRelease = toolSuiteXml.getOthers().get(0);
    assertThat(oldRelease.getDownloads().size(), equalTo(17));
    assertThat(oldRelease.getWhatsnew(), notNullValue());
}

示例7: setUp

import com.fasterxml.jackson.dataformat.xml.XmlMapper; 
@Before
public void setUp() throws Exception {
    String responseXml = Fixtures.load("/fixtures/tools/eclipse.xml");
    XmlMapper serializer = new XmlMapper();
    EclipseXml eclipseXml = serializer.readValue(responseXml, EclipseXml.class);
    eclipseDownloads = new EclipseDownloadsXmlConverter().convert(eclipseXml);
    platforms = eclipseDownloads.getPlatforms();
}

示例8: unmarshal

import com.fasterxml.jackson.dataformat.xml.XmlMapper;

@Test
public void unmarshal() throws Exception {
    XmlMapper serializer = new XmlMapper();

    EclipseXml eclipseXml = serializer.readValue(responseXml, EclipseXml.class);
    assertThat(eclipseXml.getEclipseXmlProducts(), notNullValue());
    assertThat(eclipseXml.getEclipseXmlProducts().size(), equalTo(6));

    EclipseXmlProduct eclipseXmlProduct = eclipseXml.getEclipseXmlProducts().get(0);
    assertThat(eclipseXmlProduct.getName(), equalTo("SpringSource Tool Suites Downloads"));
    assertThat(eclipseXmlProduct.getPackages().size(), equalTo(4));
    assertThat(
            eclipseXmlProduct.getPackages().get(0).getDescription(),
            equalTo("Spring Tool Suite&trade; (STS) provides the best Eclipse-powered development environment for building Spring-based enterprise applications. STS includes tools for all of the latest enterprise Java and Spring based technologies. STS supports application targeting to local, and cloud-based servers and provides built in support for vFabric tc Server. Spring Tool Suite is freely available for development and internal business operations use with no time limits."));
    assertThat(eclipseXmlProduct.getPackages().get(0).getEclipseXmlDownloads().get(0).getFile(),
            equalTo("release/STS/3.3.0/dist/e4.3/spring-tool-suite-3.3.0.RELEASE-e4.3-win32-installer.exe"));
}

示例9: deserialize

import com.fasterxml.jackson.dataformat.xml.XmlMapper;
/**
 * Deserialize the given XML string to Java object.
 *
 * @param <T> Type
 * @param body The XML string
 * @param returnType The type to deserialize into
 * @return The deserialized Java object
 */
@SuppressWarnings("unchecked")
public <T> T deserialize(String body, Type returnType) throws ApiException {
    try {
        XmlMapper xmlMapper = new XmlMapper();
        return (T) xmlMapper.readValue(body, (Class) returnType);
    } catch (IOException e) {
        return readError(body, returnType);
    }
}

示例10: readError

import com.fasterxml.jackson.dataformat.xml.XmlMapper;

private  <T> T readError(String error, Type returnType) throws ApiException {
    try {
        // Fallback processing when failed to parse XML form response body:
        //   return the response body string directly for the String return type;
        //   parse response body into date or datetime for the Date return type.
        if (returnType.equals(String.class))
            return (T) error;
        XmlMapper xmlMapper = new XmlMapper();
        ErrorResponse value = xmlMapper.readValue(error, ErrorResponse.class);
        throw new ApiException(Integer.valueOf(value.getStatus()), value.getStatusText());
    } catch (NumberFormatException | IOException ea) {
       throw new ApiException(error);
    }
}

示例11: newInstance

import com.fasterxml.jackson.dataformat.xml.XmlMapper;

public static UpgradeProcessorsConfig newInstance(Path configFilePath)
    throws JsonParseException, JsonMappingException, IOException {
  JacksonXmlModule module = new JacksonXmlModule();
  module.setDefaultUseWrapper(false);
  XmlMapper xmlMapper = new XmlMapper(module);

  return xmlMapper.readValue(configFilePath.toFile(), UpgradeProcessorsConfig.class);
}

示例12: createIndexDataBean

import com.fasterxml.jackson.dataformat.xml.XmlMapper;

public static IndexDataBean createIndexDataBean(File indexSummaryPath) {
    try {
        XmlMapper xmlMapper = new XmlMapper();
        xmlMapper.configure(Feature.WRITE_XML_DECLARATION, true);
        return xmlMapper.readValue(FileUtils.readFileToString(indexSummaryPath), IndexDataBean.class);

    } catch (Exception e) {
        return null;
    }
}

示例13: convertRequest

import com.fasterxml.jackson.dataformat.xml.XmlMapper;

/**
 * 
 * @param inputStream request.getInputStream()
 * @return
 */
public static PayNativeInput convertRequest(InputStream inputStream){
    try {
        String content = IOUtils.toString(inputStream);
        
        XmlMapper xmlMapper = new XmlMapper();
        PayNativeInput payNativeInput = xmlMapper.readValue(content, PayNativeInput.class);
        
        return payNativeInput;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

示例14: process

import com.fasterxml.jackson.dataformat.xml.XmlMapper;

@Override
public void process(Exchange exchange) throws Exception {
    LOGGER.info("Got Message from exchange!!");
    Message msg = exchange.getIn();

    String msgBody = msg.getBody().toString();
    //LOGGER.info("Message:"+ msgBody);
    XmlMapper xmlMapper = new XmlMapper();
    TableQrns tableQrns = xmlMapper.readValue(msgBody, TableQrns.class);
    final int objectId = tableQrns.getObjectId();
    LOGGER.info("ObectId {}", objectId);
    String tableName="";
    if(!TABLE_NAME_CACHE.isEmpty() && TABLE_NAME_CACHE.containsKey(Integer.valueOf(objectId))){
        tableName = TABLE_NAME_CACHE.get(Integer.valueOf(objectId));
    }else{
        // query the database table for getting table metadata by objectId
        List<TableObjectsDTO> tableObjectsDTO = (List<TableObjectsDTO>)getOraJdbcTemplate().query(SQL_META_DATA, new Object[]{objectId}, new TableRowMapper());
        tableName = tableObjectsDTO.get(0).getTableName();
        TABLE_NAME_CACHE.put(objectId, tableName);
        List<String> colNames = new ArrayList<String>();
        tableObjectsDTO.forEach(
                p->{
                    colNames.add(p.getColumnName());
                }
        );
        TABLE_META_DATA.put(tableName, colNames);
    }

    importToES(tableQrns, tableName);
}

示例15: xmlToBean

import com.fasterxml.jackson.dataformat.xml.XmlMapper;

public static <T> T xmlToBean(InputStream src, Class<T> valueType) {
    XmlMapper xml = new XmlMapper();
    try {
        return xml.readValue(src, valueType);
    } catch (IOException e) {
        Logger.getLogger(JacksonXmlUtil.class.getName()).log(Level.SEVERE, null, e);
        return null;
    }
}

示例16: main

import com.fasterxml.jackson.dataformat.xml.XmlMapper;

/**
 * @param args
 * @throws IOException
 */
public static void main(String[] args) throws IOException {
    List<Test> list = new ArrayList<>();

    Test test = new Test();
    test.setName("doctor");
    Map<String, String> map = new HashMap<>();
    map.put("age", "16");
    map.put("ke", "vv");
    test.setMap(map);
    list.add(test);

    Test test2 = new Test();
    test2.setName("doctor22");
    Map<String, String> map2 = new HashMap<>();
    map2.put("age2", "162");
    map2.put("ke2", "vv2");
    test2.setMap(map2);
    list.add(test2);

    XmlMapper xmlMapper = new XmlMapper();
    String xml = xmlMapper.writeValueAsString(list);
    System.out.println(xml);
    List<Test> ls = xmlMapper.readValue(xml, new TypeReference<List<Test>>() {
    });
    Test t = ls.get(0);
    System.out.println(t);
    System.out.println(t.getName());
    System.out.println(t.getMap());

}

示例17: testXml2Bean

import com.fasterxml.jackson.dataformat.xml.XmlMapper;

@Test
public void testXml2Bean() throws IOException {
    XmlMapper xmlMapper = new XmlMapper();
    RefundQueryWrapper refundQueryWrapper =  xmlMapper.readValue(getXml(), RefundQueryWrapper.class);
    Assert.assertNotNull(refundQueryWrapper);
    Assert.assertNotNull(refundQueryWrapper.getRefundQuery());
    refundQueryWrapper.ready();
    Assert.assertNotNull(refundQueryWrapper.getRefundQuery().getRefunds());
    Assert.assertEquals(2, refundQueryWrapper.getRefundQuery().getRefunds().size());
}

示例18: testUnwrappedWithAny

import com.fasterxml.jackson.dataformat.xml.XmlMapper;

@Test
public void testUnwrappedWithAny() throws Exception {
    final XmlMapper mapper = new XmlMapper();
    final String xml = "<xml>\n" +
            "<type>type</type>\n" +
            "<x>10</x>\n" +
            "<y>10</y>\n" +
            "<k1>k1</k1>\n" +
            "<k2>k1</k2>\n" +
            "<k3>k1</k3>\n" +
            "</xml>";

    Bean349 value = mapper.readValue(xml, Bean349.class);
    Assert.assertNotNull(value);
}

示例19: testXml2Bean

import com.fasterxml.jackson.dataformat.xml.XmlMapper;

@Test
public void testXml2Bean() throws IOException {
    XmlMapper xmlMapper = new XmlMapper();
    RefundQueryWrapper refundQueryWrapper =  xmlMapper.readValue(getXml(), RefundQueryWrapper.class);
    Assert.assertNotNull(refundQueryWrapper);
    Assert.assertNotNull(refundQueryWrapper.getRefundQuery());

}

示例20: fromXML

import com.fasterxml.jackson.dataformat.xml.XmlMapper;

@Override
public T fromXML(String xml) {
    T obj = null;
    if (StringUtils.isNotBlank(xml)) {
        XmlMapper mapper = new XmlMapper();
        try {
            obj = mapper.readValue(xml, getDomainClass());
        } catch (IOException e) {
            log.warn("Could not deserialize xml", e);
            obj = null;
        }
    }
    return obj;
}

示例21: toODataErrorFromXML

import com.fasterxml.jackson.dataformat.xml.XmlMapper;

protected XMLODataError toODataErrorFromXML(final InputStream input) {
    try {
        final XmlMapper xmlMapper = new XmlMapper(
                new XmlFactory(new InputFactoryImpl(), new OutputFactoryImpl()), new JacksonXmlModule());
        return xmlMapper.readValue(input, XMLODataError.class);
    } catch (Exception e) {
        throw new IllegalArgumentException("While deserializing XML error", e);
    }
}

示例22: hasError

import com.fasterxml.jackson.dataformat.xml.XmlMapper;

@Override
public boolean hasError(ClientHttpResponse response) throws IOException {

    if (super.hasError(response)) {
        return true;
    }

    // if response is successfully mapped to SlideShareServiceError, the response is error response
    XmlMapper xmlMapper = JacksonUtils.XML_MAPPER;
    SlideShareServiceError error = xmlMapper.readValue(response.getBody(), SlideShareServiceError.class);
    if (error != null && error.getMessage() != null) {
        return true;
    }
    return false;
}

示例23: handleError

import com.fasterxml.jackson.dataformat.xml.XmlMapper;

@Override
public void handleError(ClientHttpResponse response) throws IOException {

    XmlMapper xmlMapper = JacksonUtils.XML_MAPPER;
    SlideShareServiceError error = xmlMapper.readValue(response.getBody(), SlideShareServiceError.class);
    SlideShareServiceErrorCode errorCode = error.getErrorCode();
    String message = "SlideShare API returned error response: " + errorCode;
    throw new SlideShareServiceErrorException(error.getErrorCode(), message);
}

示例24: parse

import com.fasterxml.jackson.dataformat.xml.XmlMapper;

@SuppressWarnings("unchecked")
public static <T> T parse(byte[] xml, Class<T> valueType) {
    try {

        XmlMapper mapper = new XmlMapper();
        return mapper.readValue(xml, valueType);

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

示例25: toODataErrorFromXML

import com.fasterxml.jackson.dataformat.xml.XmlMapper;

private static XMLODataError toODataErrorFromXML(final InputStream input) {
    try {
        final XmlMapper xmlMapper = new XmlMapper(
                new XmlFactory(new InputFactoryImpl(), new OutputFactoryImpl()), new JacksonXmlModule());
        return xmlMapper.readValue(input, XMLODataError.class);
    } catch (Exception e) {
        throw new IllegalArgumentException("While deserializing XML error", e);
    }
}

示例26: loadSquadTemplates

import com.fasterxml.jackson.dataformat.xml.XmlMapper;

private void loadSquadTemplates() {
    
    Bundle templateBundle = Platform.getBundle("us.nineworlds.xstreamer.templates");
    IPath templatePath = new Path("templates/squads/templates.xml");
    
    try {
        File templateFile = FileLocator.getBundleFile(templateBundle);
        File squadTemplatesFile = new File(templateFile, templatePath.toString());
        XmlMapper mapper = new XmlMapper();
        
        Templates templates = mapper.readValue(squadTemplatesFile, Templates.class);
        squadTemplates = templates.getTemplates();
        
    } catch (IOException e) {
        e.printStackTrace();
    }
}

示例27: parse

import com.fasterxml.jackson.dataformat.xml.XmlMapper;

public void parse(String xml) throws Exception {
    XmlMapper mapper = new XmlMapper();
    Employee employee = mapper.readValue(xml, Employee.class);
    System.out.println(getClass().getSimpleName() + " " + employee.name);
}

示例28: parse

import com.fasterxml.jackson.dataformat.xml.XmlMapper; //導入方法依賴的package包/類
public void parse(String xml) throws Exception {
    XmlMapper mapper = new XmlMapper();
    Feed feed = mapper.readValue(xml, Feed.class);
    System.out.println(getClass().getSimpleName() + " " + feed);
}

示例29: testGetAndPostArticleViaXml

import com.fasterxml.jackson.dataformat.xml.XmlMapper;

@Test
public void testGetAndPostArticleViaXml() throws Exception {

    // /
    // Test initial data:
    // /
    String response = ninjaTestBrowser.makeXmlRequest(getServerAddress()
            + "api/[email protected]/articles.xml");
    System.out.println("response xml: " + response);
    
    JacksonXmlModule module = new JacksonXmlModule();
    // and then configure, for example:
    module.setDefaultUseWrapper(false);
    XmlMapper xmlMapper = new XmlMapper(module);
    

    ArticlesDto articlesDto = xmlMapper.readValue(response, ArticlesDto.class);

    assertEquals(3, articlesDto.articles.size());

    // /
    // Post new article:
    // /
    ArticleDto articleDto = new ArticleDto();
    articleDto.content = "contentcontent";
    articleDto.title = "new title new title";

    response = ninjaTestBrowser.postXml(getServerAddress()
            + "api/[email protected]/article.xml", articleDto);

    assertTrue(response.contains("Error. Forbidden."));

    doLogin();

    response = ninjaTestBrowser.postXml(getServerAddress()
            + "api/[email protected]/article.xml", articleDto);

    assertFalse(response.contains("Error. Forbidden."));

    // /
    // Fetch articles again => assert we got a new one ...
    // /
    response = ninjaTestBrowser.makeXmlRequest(getServerAddress()
            + "api/[email protected]/articles.xml");

    articlesDto = xmlMapper.readValue(response, ArticlesDto.class);
    // one new result:
    assertEquals(4, articlesDto.articles.size());

}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值