Bootstrap

JNI开发使用jsoncpp

在 Android JNI 开发中,如果使用 jsoncpp 库来生成和解析 JSON 数据,可以通过以下步骤进行集成。jsoncpp 是一个流行的 C++ JSON 库,可以方便地用于处理 JSON 数据

  1. 下载jsoncpp源码
    https://github.com/open-source-parsers/jsoncpp

  2. 手动将 jsoncpp 源代码文件加入到项目
    2.1. src\lib_json目录copy到项目main/cpp目录
    2.2. include\json目录copy到项目main/cpp目录

  3. 修改 CMakeLists.txt

    add_library( # Sets the name of the library.
            lib_json
    
            # Sets the library as a shared library.
            SHARED
    
            # Provides a relative path to your source file(s).
            lib_json/json_reader.cpp lib_json/json_tool.h lib_json/json_value.cpp lib_json/json_valueiterator.inl lib_json/json_writer.cpp)
       
    include_directories( ${CMAKE_SOURCE_DIR}/include)
       
    target_link_libraries( # Specifies the target library.
    	...
       lib_json
       # Links the target library to the log library
       # included in the NDK.
       ${log-lib})
    
  4. 在 JNI 中使用 jsoncpp 生成和解析 JSON 数据

    #include <jni.h>
    #include <string>
    #include <json/json.h>
    
    // 生成 JSON 数据的示例
    extern "C"
    JNIEXPORT jstring JNICALL
    Java_com_example_myjniapp_MainActivity_generateJson(JNIEnv *env, jobject /* this */) {
        // 创建一个 JSON 对象
        Json::Value root;
        root["name"] = "John Doe";
        root["age"] = 30;
        root["is_student"] = false;
    
    	// 创建一个 JSON 数组
        Json::Value jsonArray;
        // 向数组中添加元素
        jsonArray.append("Apple");
        jsonArray.append("Banana");
        jsonArray.append("Cherry");
    
        // 创建一个 JSON 对象并向其中添加数组
        root["fruits"] = jsonArray;
    	
        // 将 JSON 对象转换为字符串
        Json::StreamWriterBuilder writer;
        std::string json_string = Json::writeString(writer, root);
    
        // 返回给 Java 层
        return env->NewStringUTF(json_string.c_str());
    }
    
    // 解析 JSON 数据的示例
    extern "C"
    JNIEXPORT jstring JNICALL
    Java_com_example_myjniapp_MainActivity_parseJson(JNIEnv *env, jobject /* this */, jstring jsonStr) {
        // 获取 Java 字符串并转换为 C++ 字符串
        const char *json_data = env->GetStringUTFChars(jsonStr, nullptr);
        std::string json_string(json_data);
    
        // 解析 JSON 字符串
        Json::CharReaderBuilder reader;
        Json::Value root;
        std::string errs;
        std::istringstream sstream(json_string);
        if (!Json::parseFromStream(reader, sstream, &root, &errs)) {
            return env->NewStringUTF("Failed to parse JSON");
        }
    
        // 从解析后的 JSON 数据中获取字段
        std::string name = root["name"].asString();
        int age = root["age"].asInt();
        bool is_student = root["is_student"].asBool();
    
        // 构建返回字符串
        std::string result = "Name: " + name + ", Age: " + std::to_string(age) + ", Is Student: " + (is_student ? "Yes" : "No");
    
        // 释放 Java 字符串资源
        env->ReleaseStringUTFChars(jsonStr, json_data);
    
        return env->NewStringUTF(result.c_str());
    }
    
    
;