iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >java解析多层嵌套json字符串问题
  • 757
分享到

java解析多层嵌套json字符串问题

2024-04-02 19:04:59 757人浏览 泡泡鱼

Python 官方文档:入门教程 => 点击学习

摘要

目录java分别解析下面两个JSON字符串嵌套(任意层)jsON解析转换为Map源代码java分别解析下面两个json字符串 package jansonDemo; import

java分别解析下面两个json字符串

img

img

package jansonDemo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
public class TestJSON {
    
    
    private static void strWritedToJSONObject() {
        //以下是一个json对象中嵌套一个json子对象
        String myJsonObj = "{\n" +
                "    \"name\":\"runoob\",\n" +
                "    \"alexa\":10000,\n" +
                "    \"sites\": {\n" +
                "        \"site1\":\"www.runoob.com\",\n" +
                "        \"site2\":\"m.runoob.com\",\n" +
                "        \"site3\":\"c.runoob.com\"\n" +
                "    }\n" +
                "}";
        JSONObject jsonobj = JSON.parseObject(myJsonObj); //将json字符串转换成jsonObject对象
        
        System.out.println(jsonobj.get("name")); //取出name对应的value值,得到的是一个object
        System.out.println(jsonobj.getString("name")); //取出name对应的value值,得到的是一个String
        System.out.println(jsonobj.getIntValue("alexa")); //取出name对应的value值,得到的是一个int
        System.out.println(jsonobj.get("sites")); //取出sites对应的value值,得到的是一个object
        System.out.println(jsonobj.getString("sites"));
        System.out.println(jsonobj.getJSONObject("sites")); //取出sites对应的value值,得到一个JSONObject子对象
        System.out.println(jsonobj.getJSONObject("sites").getString("site2")); //取出嵌套的JSONObject子对象中site2对应的value值,必须用getJSONObject()先获取JSONObject
        
        String myJsonObj2 = "{\n" +
                "    \"name\":\"网站\",\n" +
                "    \"num\":3,\n" +
                "    \"sites\": [\n" +
                "        { \"name\":\"Google\", \"info\":[ \"Android\", \"Google 搜索\", \"Google 翻译\" ] },\n" +
                "        { \"name\":\"Runoob\", \"info\":[ \"菜鸟教程\", \"菜鸟工具\", \"菜鸟微信\" ] },\n" +
                "        { \"name\":\"Taobao\", \"info\":[ \"淘宝\", \"网购\" ] }\n" +
                "    ]\n" +
                "}";
        JSONObject jsonobj2 = JSON.parseObject(myJsonObj2); //将json字符串转换成jsonObject对象
        System.out.println(jsonobj2.get("sites"));
        System.out.println(jsonobj2.getString("sites"));
        System.out.println(jsonobj2.getJSONArray("sites")); //取出sites对应的value值,得到一个JSONOArray对象
        //System.out.println(jsonobj2.getJSONObject("sites")); 不能用该方法,因为sites是一个JSONOArray对象
        //取出json对象中sites对应数组中第一个json子对象的值
        System.out.println(jsonobj2.getJSONArray("sites").getJSONObject(0)); //得到结果:{"name":"Google","info":["Android","Google 搜索","Google 翻译"]}
        System.out.println(jsonobj2.getJSONArray("sites").get(0));
        System.out.println(jsonobj2.getJSONArray("sites").getString(0));
        //取出json对象中sites对应数组中第一个json子对象下面info对应的嵌套子数组值
        System.out.println(jsonobj2.getJSONArray("sites").getJSONObject(0).getJSONArray("info")); //得到结果:["Android","Google 搜索","Google 翻译"]
        //取出json对象中sites对应数组中第一个json子对象下面info对应的嵌套子数组中第二个值
        System.out.println(jsonobj2.getJSONArray("sites").getJSONObject(0).getJSONArray("info").getString(1)); //得到结果:Google 搜索
        //依次取出json对象中sites对应数组中的值
        JSONArray array = jsonobj2.getJSONArray("sites");
        getJsonArrayItem(array);
        //依次取出json对象中sites对应数组中第二个json子对象下面info对应的嵌套子数组值
        JSONArray arr = jsonobj2.getJSONArray("sites").getJSONObject(1).getJSONArray("info");
        getJsonArrayItem(arr);
     }
    
    private static void writeStrToJSONObject() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name","tom");
        jsonObject.put("age",20);
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonArrayObject1 = new JSONObject();
        jsonArrayObject1.put("name","alibaba");
        jsonArrayObject1.put("info","www.alibaba.com");
        JSONObject jsonArrayObject2 = new JSONObject();
        jsonArrayObject2.put("name","baidu");
        jsonArrayObject2.put("info","www.baidu.com");
        jsonArray.add(jsonArrayObject1);
        jsonArray.add(jsonArrayObject2);
        jsonObject.put("sites",jsonArray);
        System.out.println(jsonObject);
     }
    
    private static void strToJsonArray() {
        String arrayStr = "[\n" +
                "        {\n" +
                "            \"name\":\"alibaba\",\n" +
                "            \"info\":\"www.alibaba.com\"\n" +
                "        },\n" +
                "        {\n" +
                "            \"name\":\"baidu\",\n" +
                "            \"info\":\"www.baidu.com\"\n" +
                "        }\n" +
                "    ]";
        JSONArray array = JSON.parseArray(arrayStr);
        System.out.println(array);
     }
    
    private static void getJsonArrayItem(JSONArray array) {
        for (int i=0; i<array.size(); i++) {
            System.out.println(array.get(i));
        }
    }
     //测试类
    public static void main(String[] args) {
        strWritedToJSONObject();
        //writeStrToJSONObject();
        //strToJsonArray();
    }
}

嵌套(任意层)JSON解析转换为Map

最近需要检验系统多次返回的json结果是否相同,以保证系统升级后的功能一致,所以产生了编写json转换程序的需求。

由于小弟编程能力尚浅,有些特殊情况的转换没能考虑好,希望各位可以提出,或者贴出更完善的解析程序供大家分享,先在此处抛砖引玉了。

以下程序用于把多层嵌套的json字符串转换为平层的Map,以方便在后续的测试程序中对比结果。

源代码


import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import java.util.*;
import java.util.Map.Entry;

public class JsonParseUtil {
    public static String checkFORMat(String str){
        String _str = str.trim();
        if(_str.startsWith("[") && _str.endsWith("]")){
            return  _str.substring(1,_str.length()-1);
        }
        return  _str;
    }
    
    public static void printJsonMap(Map map){
        Set entrySet = map.entrySet();
        Iterator<Map.Entry<String, Object>> it = entrySet.iterator();
        //最外层提取
        while(it.hasNext()){
            Map.Entry<String, Object> e = it.next();
            System.out.println("Key 值:"+e.geTKEy()+"     Value 值:"+e.getValue());
        }
    }
    
    public static void parseJSON2Map(Map jsonMap,String jsonStr,String parentKey){
        //字符串转换成JSON对象
        JSONObject json = JSONObject.fromObject(jsonStr);
        //最外层JSON解析
        for(Object k : json.keySet()){
            //JSONObject 实际上相当于一个Map集合,所以我们可以通过Key值获取Value
            Object v = json.get(k);
            //构造一个包含上层keyName的完整keyName
            String fullKey = (null == parentKey || parentKey.trim().equals("") ? k.toString() : parentKey + "." + k);
            if(v instanceof JSONArray){
                 //如果内层还是数组的话,继续解析
                Iterator it = ((JSONArray) v).iterator();
                while(it.hasNext()){
                    JSONObject json2 = (JSONObject)it.next();
                    parseJSON2Map(jsonMap,json2.toString(),fullKey);
                }
            } else if(isNested(v)){
                parseJSON2Map(jsonMap,v.toString(),fullKey);
            }
            else{
                jsonMap.put(fullKey, v);
            }
        }
    }
    public static boolean isNested(Object jsonObj){
        return jsonObj.toString().contains("{");
    }
    public static void println(Object str){
        System.out.println(str);
    }
}

测试程序:

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import java.util.*;
import java.util.Map.Entry;

public class JsonParseUtil {
    public static void main(String[] args) throws Exception {
        JsonParseUtil jsonParseUtil = new JsonParseUtil();
        jsonParseUtil.test();
    }
    public void test(){
        //JSON类型的字符串
        String strJson = "{a:1,b:2,c:3,d:[{a1:11,a2:22,a3:33},{a1:{a2:222,a3:333}}]}";
        Map jsonMap = new HashMap();
        parseJSON2Map(jsonMap,checkFormat(strJson),null);
        printJsonMap(jsonMap);
    }
}

测试结果:

Key 值:a     Value 值:1
Key 值:b     Value 值:2
Key 值:d.a3     Value 值:33
Key 值:c     Value 值:3
Key 值:d.a1     Value 值:11
Key 值:d.a2     Value 值:22
Key 值:d.a1.a3     Value 值:333
Key 值:d.a1.a2     Value 值:222

以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。

--结束END--

本文标题: java解析多层嵌套json字符串问题

本文链接: https://www.lsjlt.com/news/168823.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作