Java 使用Gson處理多層json格式的value和key值


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依賴

        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.2</version>
        </dependency>

添加包

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)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM