Managed Package有许多限制,比如无法在外部/本地代码中序列化受控包中的Apex Class

JSON Support Considerations

Only custom objects, which are sObject types, of managed packages can be serialized from code that is external to the managed package. Objects that are instances of Apex classes defined in the managed package can't be serialized.

假如有个包Px,命名空间Px。我们有个Apex Class需要调用里面的对象并JSON序列化。

直接JSON序列化是不行的

包中代码:

//Inside package Px
global class C {
  global String stringA;
  global Integer StringB;
}

本地代码调用,会失败:

@isTest
private class TestFromLocal {
    @isTest static void testSerialize() {
    try{ 
      JSON.serialize(new Px.C());
      System.assert(false,'This should fail');
    } catch (Exception ex) {
      System.assertEquals('Cannot serialize type from package: Px.C',ex.getMessage());
    }
  }
}

但是可以通过扩展Apex Class来序列化

我们可以利用扩展(extends)一个虚拟类(virtual class)来实现序列化!

1. 保证需要序列化的Class是virtual

包中代码:

//Inside package Px
global virtual class C {
  global String stringA;
  global Integer StringB;
}

2. extends it!

@isTest
private class TestFromLocal {

class Ext extends Px.C { }

@isTest static void testSerialize() {
  Ext virt = new Ext();
  virt.stringA = 'bla';
  virt.IntgerB = 1;
  System.assertEquals('{"stringA":"bla", "IntgerB": 1}',JSON.serialize(virt));
}

}

这样就可以正常调用了!

参考

1.Salesforce: Serializing Objects from a Managed Package

标签: none

添加新评论