如何在 java 中去掉 json 外层对象
原始 json 数据结构中有一个名为 "other" 的外层对象,需要将其移除而保留原始数据。
import com.google.gson.gson; import com.google.gson.gsonbuilder; import com.google.gson.jsonelement; import com.google.gson.jsonobject; public class removeouterobject { public static void main(string[] args) { string json = "{\"other\": {\"name\": \"john doe\", \"age\": 30}}"; gson gson = new gsonbuilder() // 使用 fieldnamingpolicy.upper_camel_case 命名策略将外层对象属性转为字段名 .setfieldnamingpolicy(fieldnamingpolicy.upper_camel_case) .create(); // 将 json 字符串解析为 jsonelement 对象 jsonelement jsonelement = gson.fromjson(json, jsonelement.class); // 获取外层对象 jsonobject outerobject = jsonelement.getasjsonobject(); // 获取原始数据并转换为 string string data = outerobject.remove("other").tostring(); system.out.println(data); } }
最终输出结果:
{"name": "John Doe", "age": 30}
以上就是Java中如何移除JSON外层对象并保留内部数据?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号