前言

       今日在做JSON字符串,转为对象的操作失败,特此做个记录,以防日后再次踩坑。

正文

       错误信息:

com.alibaba.fastjson.JSONException: not match : - =, info : pos 3, line 1, column 4{id=66, firmware_id=15, version=V20190617_170943, file_hash=c9782aeff870c229f4a9d3efbaa11fa7, file_size=511020, description=测试, product_id=8}

       错误代码:

//使用JSONObject进行了数据库接收
String test1(@RequestBody JSONObject jsonObject){
    String versionInfoStr = jsonObject.getString("versionInfo");
    VersionInfo versionInfo = JSONObject.parseObject(versionInfoStr, VersionInfo.class);
    return null;
}

       正确代码:

//改成String接收的就不会出现错误
String test20190624_02(@RequestBody String str){
    JSONObject jsonObject = JSONObject.parseObject(str);
    String versionInfoStr = jsonObject.getString("versionInfo");
    VersionInfo versionInfo = JSONObject.parseObject(versionInfoStr, VersionInfo.class);
    return null;
}

       主要的问题就出现在getString这句代码

错误代码中getString得到的值为
    {id=66, firmware_id=15, version=V20190617_170943, file_hash=c9782aeff870c229f4a9d3efbaa11fa7, file_size=511020, description=测试, product_id=8}

而正确代码中得到的是
    {"id":"66","firmware_id":"15","version":"V20190617_170943","file_hash":"c9782aeff870c229f4a9d3efbaa11fa7","file_size":"511020","description":"测试","product_id":"8"}

       可以看出前者省去了双引号,不是一个正确的JSON字符串,这才导致转换成对象出现异常。

GitHub 加速计划 / js / json
18
5
下载
适用于现代 C++ 的 JSON。
最近提交(Master分支:3 个月前 )
2134cb94 * change NLOHMANN_JSON_FROM_WITH_DEFAULT to let NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT work with an empty JSON instance * fix ci_static_analysis_clang (ci_clang_tidy) * change NLOHMANN_JSON_FROM_WITH_DEFAULT to let NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT work with an empty JSON instance 8 天前
6057b31d * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * Use ubuntu-latest image to run Valgrind (#4575) * :wrench: use Clang image to run valgrind * :wrench: use Clang image to run valgrind * :wrench: use Clang image to run valgrind * :wrench: use Ubuntu image to run valgrind * Use Clang image to run iwyu (#4574) * :wrench: use Clang image to run iwyu * :wrench: use Clang image to run iwyu * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :art: format code * :hammer: clean up 10 天前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐