Trying to understand why simple jsonix unmarshalli

2019-07-13 05:31发布

问题:

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);


标签: jsonix