Tool method: The purpose of this article is to convert the json string into map key-value pair storage, and only store the data of the leaf node
maven references the 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.*; import java.util.*; /** * Created by BF100 on 2018/4/12. */ @Slf4j public class TestByCaoxNew { @Test 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/":/"success! /"}"; String str2 = "{result:success,message:success}"; // 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 json object data in 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:{China:{numFound:9,startOffset:0,endOffset:2," + "suggestion:[Industrial and Commercial Bank of China, Chinese People, China International, China Agriculture, China Market, China Economy, Chinese People, China Broadcast, Chinese Culture]}}," + "collations:{collation:Industrial and Commercial Bank of China}}}"; 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)); } } }Summarize
The above is the method of converting json objects into map key-value pairs introduced by the editor. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support to Wulin.com website!