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

 

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

img

img

package jansonDemo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
public class TestJSON {
  /**
   * JSON实际上也是键值对("key":"value")
   * key 必须是字符串,value 可以是合法的 JSON 数据类型(字符串, 数字, 对象, 数组, 布尔值或 null)
   * value如果是字符串,用jsonobj.getString("key")获取
   * value如果是数  字,用jsonobj.getIntValue("key"),jsonobj.getFloatValue("key"),jsonobj.getInteger("key")等基本数据类型及其包装类的方法获取
   * value如果是布尔值,用jsonobj.getBoolean("key"),jsonobj.getBooleanValue("key")获取
   * value如果是数  组,用jsonobj.getJSONArray("key")获取
   * value如果是Object对象,用jsonobj.get("key"),获取
   * value如果是JSONObject对象,用jsonobj.getJSONObject("key")获取
   */
  /**
   * 该方法用于将已有的json字符串转换为json对象,并取出该对象中相应的key对应的value值
   * 将已有的字符串转换成jsonobject,用JSON.parseObject(jsonStr)方法
   * json中只要是{}就代表一个JSONObject,[]就代表一个JSONArray
   * 获取JSONObject对象用JSONObject jsonobject.getJSONObject("key")方法
   * 获取JSONArray对象用JSONObject jsonobject.getJSONArray("key")方法
   */
  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对象
      /***获取JSONObject中每个key对应的value值时,可以根据实际场景中想得到什么类型就分别运用不到的方法***/
      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
      /**
       * 以下是一个json对象中包含数组,数组中又包含json子对象和子数组
       */
      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);
   }
  /**
   * 手动添加对象到一个JSONObject
   */
  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);
   }
  /**
   * 将字符串转为JSONArray
   */
  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);
   }
  /**
   * 依次取出JSONArray中的值
   */
  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;
/**
* Created by chenyuzhi on 17-8-12.
*/
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;
  }
  /**
   * 打印Map中的数据
   * @param map
   */
  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());
      }
  }
  /**
   * JSON 类型的字符串转换成 Map
   */
  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;
/**
 * Created by chenyuzhi on 17-8-12.
 */
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

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

本文通过优化买票的重复流程来说明享元模式,为了加深对该模式的理解,会以String和基本数据类型的包装类对该模式的设计进一步说明。读者可以拉取完整代码到本地进行学习,实现代码均测试通过后上传到码云。 一 ...