Using org.json.JSONObject;
Current code
Java Code:
class sample
{
int val = 7;
String str = "Hai";
public native void callCpp(JSONObject jo);
public static void main(String args[])
{
sample s = new sample();
JSONObject jo = new JSONObject();
jo.put("val",val);
jo.put("str",str);
s.callCpp(jo);
}
}
CPP Code:
JNIEXPORT void JNICALL Java_sample_callCpp(JNIEnv *env, jobject obj, jobject jobj)
{
jclass cls = env->FindClass("org/json/JSONObject");
jmethodID method = env->GetMethodID(cls, "getInt", "(Ljava/lang/String;)I");
jint val = env->CallIntMethod(arg, method, env->NewStringUTF("val"));
std::cout << "val: " << val << std::endl;
jmethodId method2 = env->GetMethodID(cls, "getString", "(Ljava/lang/String;)Ljava/lang/String;");
jstring strVal = (jstring) env->CallObjectMethod(arg, method2, env->NewStringUTF("strVal"));
const jchar *ptr = env->GetStringUTFChars(strVal, nullptr);
std::string strVal_copy(ptr);
env->ReleaseStringUTFChars(strVal, ptr);
std::cout << "strVal: " << strVal_copy << std::endl;
}
From this I can retrieve "val
" and "str
" and use in CPP
.
But my problem is, I cannnot do the exact oppposite of this.
I need to send values to "val" and "str" to that JSONObject.
The following seems to be wrong, Help me correct it!
JAVA CODE:
void valFromCPP(JSONObject jo)
{
System.out.println("Val is :: " + jo.getInt("val"));
System.out.println("Str is :: " + jo.getString("str"));
}
CPP CODE:
JNIEXPORT void JNICALL Java_sample_disp(JNIEnv *env, jobject cobj, jobject jsonjobj)
{
jclass jsoncls = env->FindClass("org/json/JSONObject");
jclass ccls = env->GetObjectClass(cobj);
jobject newObj;
jmethodID constructorID = env->GetMethodID(jsoncls,"<init>","()V");
newObj = env->NewObject(jsoncls, constructorID);
jmethodID putStringID = env->GetMethodID(jsoncls, "put", "(Ljava/lang/String;Ljava/lang/Object;)Lorg/json/JSONObject;");
if(putStringID == NULL)
{
printf("\n putStringID not created!\n");
return;
}
jmethodID putIntID = env->GetMethodID(jsoncls, "put", "(Ljava/lang/String;I)Lorg/json/JSONObject;");
jmethodID valFromCPPId = env->GetMethodID(ccls, "valFromCPP", "(Lorg/json/JSONObject;)V");
newObj = env->CallObjectMethod(newObj, putStringID, env->NewStringUTF("str"), env->NewStringUTF("Hai"));
newObj = env->CallObjectMethod(newObj, putIntID, env->NewStringUTF("val"), 7);
env->CallVoidMethod(cobj, valFromCPPId, newObj);
}
Im getting the error :
putStringID Not Created
Exception in thread "main" java.lang.NoSuchMethodError: put
Even though i made sure there is put method, and it returns "this", which is that object.