Tool method: The purpose of this article is to convert the json string into a map key-value pair storage, and only store the data of the leaf nodes
maven reference jar package version:
- <dependency>
- <groupId>org.json</groupId>
- <artifactId>json</artifactId>
- <version>20090211</version>
- </dependency>
Tools:
- package com.baofoo.admin.test;
- //import com.alibaba.fastjson.JSONObject;
- import lombok.extern.slf4j.Slf4j;
- import org.junit.Test;
- import org.json.*; Jiangsu Surrogacy
- import java.util.*; Jiangsu Surrogacy Company
- /**
- * Created by BF100 on 2018/4/12.
- */
- @ Slf4j
- public class TestByCaoxNew {
- [url=home.php?mod=space&uid=5447]@test[/url]
- public void test1(){
- try{
- int a = 1/0;
- }catch (Exception e){
- log.error("call Exception :{}",e);
- e.printStackTrace ();
- }
- System.out.println("come on !!!");
- }
- @Test
- public void test2() throws Exception{
- String str = "{\"result\":\"success\",\"message\":\"成功!\"}";
- String str2 = "{result:success,message:成功}";
- // JSONObject jsStr = JSONObject.parseObject(str);
- // System.out.println(jsStr);
- JSONObject obj = new JSONObject(str);
- Stack<JSONObject> stObj = new Stack<JSONObject>();
- stObj.push(obj);
- Map<String, Object> resultMap =new HashMap<String, Object>();
- JsonToMap(stObj,resultMap);
- Set<String> keys = resultMap.keySet();
- for (String key:keys){
- System.out.println(key+":"+resultMap.get(key));
- }
- }
- /**
- * @Author:sks
- * @Description: Store the json object data in the map in the form of key-value pairs, only store leaf nodes
- * @Date:
- */
- private static void JsonToMap(Stack<JSONObject> stObj, Map<String, Object> resultMap) throws Exception {
- if(stObj == null && stObj.pop() == null){
- return ;
- }
- JSONObject json = stObj.pop();
- Iterator it = json.keys();
- while(it.hasNext()){
- String key = (String) it.next();
- //get the value of value
- Object value = json.get(key);
- //System.out.println(value);
- if(value instanceof JSONObject)
- {
- stObj.push((JSONObject)value);
- // recursively traverse
- JsonToMap(stObj,resultMap);
- }
- else {
- resultMap.put(key, value);
- }
- }
- }
- @Test
- public void test3() throws Exception{
- String jsonStr ="{responseHeader:{status:0,QTime:0},spellcheck:{suggestions:{中国:{numFound:9,startOffset:0,endOffset:2," +
- "suggestion:[Industrial and Commercial Bank of China, Chinese People, China International, Chinese Agriculture, Chinese Market, Chinese Economy, Chinese, Chinese Broadcasting, Chinese Culture]}}," +
- "collations:{collation:ICBC}}}";
- JSONObject obj = new JSONObject(jsonStr);
- Stack<JSONObject> stObj = new Stack<JSONObject>();
- stObj.push(obj);
- Map<String, Object> resultMap =new HashMap<String, Object>();
- JsonToMap(stObj,resultMap);
- Set<String> keys = resultMap.keySet();
- for (String key:keys){
- System.out.println(key+":"+resultMap.get(key));
- }
- }
- }