首先说需求,最近接手一个项目,要在底层解析二进制数据,数据结构比较负责,由于服务器是c++服务器,加之开始没有考虑到移动端开发,所以协议有点扯蛋!大体是这样的,一个数据包里面是map里面放vector然后序列化成二进制!ios的还好弄一点,object-c本身支持c++,简单封装就可以了,android的有点麻烦,需要把数据转成java的数据格式,问题来了,c++的数据接口大体是这样的:
std::map<std::string,std::vector<struct info> > tmep;
要转换成java的数据对象,上网搜了一下,没有这方面的资料,有的基本都是一些简单的对象返回,没有这么复杂的,没法,自己动手做了,我的做法是这样的:
在java里面声明一个对象类,如下:
public class ControlDictionaryValue { public String value; }
public class LoginMsg extends BaseMsg { // 字典列表 public HashMap<String, ArrayList<ControlDictionaryValue> > controlDictionary; }
JNIEXPORT jobject JNICALL Java_com_example_filltriangle_GL2JNILib_test(JNIEnv* env, jclass tis) { jclass m_login_msg = env->FindClass("hzcw/msgdata/LoginMsg"); jmethodID m_method_login_msg_init = env->GetMethodID(m_login_msg,"<init>","()V"); jobject m_login_msg_obj = env->NewObject(m_login_msg, m_method_login_msg_init); jfieldID m_fid_controlDictionary = env->GetFieldID(m_login_msg,"controlDictionary","Ljava/util/HashMap;"); // new一个hashmap对象 jclass class_hashmap=env->FindClass("java/util/HashMap"); jmethodID hashmap_construct_method=env->GetMethodID(class_hashmap, "<init>","()V"); jobject obj_hashmap =env->NewObject(class_hashmap, hashmap_construct_method, ""); jmethodID hashmap_put_method= env->GetMethodID(class_hashmap,"put","(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;"); // new一个ArrayList对象 jclass class_arraylist=env->FindClass("java/util/ArrayList"); jmethodID arraylist_construct_method=env->GetMethodID(class_arraylist, "<init>","()V"); jobject obj_arraylist =env->NewObject(class_arraylist, arraylist_construct_method, ""); jmethodID arraylist_add_method= env->GetMethodID(class_arraylist,"add","(Ljava/lang/Object;)Z"); // new一个ControlDictionaryValue对象 jclass m_cls_ControlDictionaryValue = env->FindClass("hzcw/datastruct/ControlDictionaryValue"); jmethodID m_mid_ControlDictionaryValue = env->GetMethodID(m_cls_ControlDictionaryValue,"<init>","()V"); jobject m_obj_ControlDictionaryValue = env->NewObject(m_cls_ControlDictionaryValue, m_mid_ControlDictionaryValue, ""); // 获取ControlDictionaryValue对象的value变量 jfieldID m_fid_ControlDictionaryValue_value = env->GetFieldID(m_cls_ControlDictionaryValue,"value","Ljava/lang/String;"); env->SetObjectField(m_obj_ControlDictionaryValue,m_fid_ControlDictionaryValue_value,env->NewStringUTF("牙科")); env->CallBooleanMethod(obj_arraylist, arraylist_add_method, m_obj_ControlDictionaryValue); env->CallObjectMethod(obj_hashmap,hashmap_put_method,env->NewStringUTF((char*)"科室"), obj_arraylist); env->SetObjectField(m_login_msg_obj,m_fid_controlDictionary,obj_hashmap); env->DeleteLocalRef(m_obj_ControlDictionaryValue); //删除局部引用 env->DeleteLocalRef(obj_arraylist); //删除局部引用 env->DeleteLocalRef(obj_hashmap); //删除局部引用 return m_login_msg_obj; }以上这个是做的假数据,真实的数据自己去填充,做开发的一眼就懂的!
原文地址:http://blog.csdn.net/cjj198561/article/details/38669053