Search code examples
c++jsonjava-native-interface

Pass JSON object as argument in JNI to CPP and retrieve JSON Objects's data in CPP


Need to input data from a java program using class object, convert it to json object and pass to c++ through JNI. In C++, have to retrieve the data from the object and store it in a file.

I dont know how to send and retrieve a json object's data. Help me out with some simple code snippets!!

class sample
{  

    public native void callCPP(JSONObject jo);    
    public static void main(String args[])
    {  
        int val = 7;  
        JSONObject jo = new JSONObject;  
        jo.put("val",val);

        sample s = new sample();
        s.callCPP(jo);  
    }  
}

and the vice versa too(sending data from cpp to java as JSONObject.


Solution

  • Assuming you meant org.json.JSONObject:

    void Java_sample_callCPP(JNIEnv *env, jobject obj, jobject arg) {
        // This code calls arg->getInt("val"), assuming it is a org.json.JSONObject
        jclass cls = env->FindClass("org/json/JSONObject"); // alternatively: env->GetObjectClass(arg);
        jmethodID method = env->GetMethodID(cls, "getInt", "(Ljava/lang/String;)I"); // int getInt(java.lang.String key)
        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"));
    
        // Make a copy of the returned Java string. We need to release the pointer again, too.
        const jchar *ptr = env->GetStringUTFChars(strVal, nullptr);
        std::string strVal_copy(ptr);
        env->ReleaseStringUTFChars(strVal, ptr);
        std::cout << "strVal: " << strVal_copy << std::endl;
    }