Trying to understand why simple jsonix unmarshalling is failing

无人久伴 提交于 2019-12-23 23:20:52

问题


I am new to jsonix and interested mostly in using it to unmarshall xml data. I wrote a very basic test example but have been unsuccessful in getting it to work.

var MyModule = {
    name: 'MyModule',
    typeInfos: [{
        type: 'classInfo',
        localName: 'AnyElementType',
        propertyInfos: [{
            type: 'anyElement',
            allowDom: true,
            allowTypedObject:true,
            name: 'any',
            collection: false
        }]
    }],
    elementInfos: [{
        elementName: 'sos:Capabilities',
        typeInfo: 'MyModule.AnyElementType'
    }]
  };

  var context = new Jsonix.Context([MyModule], {namespacePrefixes:  {'http://www.opengis.net/sos/2.0':'sos'}});
  var unmarshaller = context.createUnmarshaller();
  var data = unmarshaller.unmarshalString('<sos:Capabilities version=\"2.0.0\">hello</sos:Capabilities>');
  return data;

I hardcoded a single simple element that has a namespace and contains 'hello' for the test xml. I was interested in the 'any element mapping' for generic unmarshalling. I feel like I have the namespace configured appropriately etc when creating the context yet I keep getting the following error: Element [sos:Capabilities] could not be unmarshalled as is not known in this context and the property does not allow DOM content. Thoughts? and thanks in advance.


回答1:


Disclaimer: I am the author of Jsonix.

There are two issues here.

First, you're missing xmlns:sos="http://www.opengis.net/sos/2.0" in your XML.

Second, currently you'll need to define the element name as an object with namespaceURI and localPart. If you just use string, Jsonix will use defaultElementNamespaceURI (which is not defined here). The namespacePrefixes option is currently not applied in elementInfos. This would be a fine feature, please file an issue if you want this.

Here's a working JSFiddle with you module.

var MyModule = {
  name: 'MyModule',
  typeInfos: [{
    type: 'classInfo',
    localName: 'AnyElementType',
    propertyInfos: [{
      type: 'anyElement',
      allowDom: true,
      allowTypedObject: true,
      name: 'any',
      collection: false
    }]
  }],
  elementInfos: [{
    elementName: {
      namespaceURI: 'http://www.opengis.net/sos/2.0',
      localPart: 'Capabilities'
    },
    // 'sos:Capabilities',
    typeInfo: 'MyModule.AnyElementType'
  }]
};

var context = new Jsonix.Context([MyModule], {
  namespacePrefixes: {
    'http://www.opengis.net/sos/2.0': 'sos'
  }
});
var unmarshaller = context.createUnmarshaller();
var data = unmarshaller.unmarshalString('<sos:Capabilities version=\"2.0.0\" xmlns:sos=\"http://www.opengis.net/sos/2.0\">hello</sos:Capabilities>');
console.log(data);


来源:https://stackoverflow.com/questions/37033419/trying-to-understand-why-simple-jsonix-unmarshalling-is-failing

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!