Java 使用Gson处理多层json格式的value和key值 您所在的位置:网站首页 java中获取json的key和value Java 使用Gson处理多层json格式的value和key值

Java 使用Gson处理多层json格式的value和key值

2024-06-10 09:33| 来源: 网络整理| 查看: 265

json如下:

{"words_result":{"姓名":{"location":{"top":277,"left":618,"width":372,"height":164},"words":"张三"},"民族":{"location":{"top":568,"left":1262,"width":101,"height":126},"words":"汉"},"住址":{"location":{"top":1082,"left":552,"width":1392,"height":486},"words":"住址住址住址"},"公民身份号码":{"location":{"top":1733,"left":1105,"width":1749,"height":157},"words":"***************"},"出生":{"location":{"top":814,"left":561,"width":969,"height":132},"words":"********"},"性别":{"location":{"top":561,"left":580,"width":110,"height":129},"words":"男"}},"idcard_number_type":1,"words_result_num":6,"image_status":"normal","log_id":1453528763137919643}

这个json有很多层,使用一般方法不能获取想要的value值

JSONObject jsonObject = JSONObject.fromObject(result); String value = jsonObject.getString("姓名"); System.out.println(value);

使用Gson来进行处理,

首先添加maven依赖

com.google.code.gson gson 2.8.2

添加包

import com.google.gson.JsonObject; import com.google.gson.JsonParser;

方法

JsonParser jp = new JsonParser(); //将json字符串转化成json对象 JsonObject jo = jp.parse(result).getAsJsonObject(); //获取姓名对应的值 String name = jo.get("words_result").getAsJsonObject() .get("姓名").getAsJsonObject() .get("words").getAsString(); System.out.println("姓名:" + name); //获取性别对应值 String sex = jo.get("words_result").getAsJsonObject() .get("性别").getAsJsonObject() .get("words").getAsString(); System.out.println("性别:" + sex); //获取民族对应值 String nation = jo.get("words_result").getAsJsonObject() .get("民族").getAsJsonObject() .get("words").getAsString(); System.out.println("民族:" + nation); //获取住址对应值 String address = jo.get("words_result").getAsJsonObject() .get("住址").getAsJsonObject() .get("words").getAsString(); System.out.println("住址:" + address); //获取出生日期对应值 String birth = jo.get("words_result").getAsJsonObject() .get("出生").getAsJsonObject() .get("words").getAsString(); System.out.println("出生日期:" + birth); //获取身份证对应值 String id = jo.get("words_result").getAsJsonObject() .get("公民身份号码").getAsJsonObject() .get("words").getAsString(); System.out.println("姓名:" + id);

 

输出结果

参考:java 获取json字符串中key对应的值 - 小猫钓鱼吃鱼 - 博客园 (cnblogs.com)

 



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有