公司项目用的IBM封装的json解析,此处采用阿里的fastjson进行演示,代码如下:
package com.alphajuns.test; import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.junit.Test; import java.util.Map; /**
* @ClassName JsonToMapTest
* @Description
* @Author AlphaJunS
* @Date 2019/10/23 22:34
* @Version V1.0
**/
public class JsonToMapTest { /**
* @description json字符串转json数组
* @author AlphaJunS
* @date 2019/10/23
* @param []
* @return void
*/
@Test
public void run3() {
// json字符串
String jsonStr = "[{\"ID\":\"SX5-1001432\",\"PROCESSID\":\"OP2080\"}, "
+ "{\"ID\":\"SX5-1601110\",\"PROCESSID\":\"OP2150\"}, "
+ "{\"ID\":\"X03004-1023111\",\"PROCESSID\":\"OP1140\"}, "
+ "{\"ID\":\"X03004-1003012\",\"PROCESSID\":\"GOP260\"}, "
+ "{\"ID\":\"7903075118\",\"PROCESSID\":\"GOP260\"},{\"ID\":\"13MA-11011\"}]";
JSONArray jsonArray = JSON.parseArray(jsonStr);
// 遍历打印
printMethod(jsonArray);
} /**
* @description
* @author AlphaJunS
* @date 2019/10/23
* @param []
* @return void
*/
@Test
public void run2() {
// json字符串
String jsonStr = "{\"OPERATION\":[{\"ID\":\"SX5-1001432\",\"PROCESSID\":\"OP2080\"}, "
+ "{\"ID\":\"SX5-1601110\",\"PROCESSID\":\"OP2150\"}, "
+ "{\"ID\":\"X03004-1023111\",\"PROCESSID\":\"OP1140\"}, "
+ "{\"ID\":\"X03004-1003012\",\"PROCESSID\":\"GOP260\"}, "
+ "{\"ID\":\"7903075118\",\"PROCESSID\":\"GOP260\"},{\"ID\":\"13MA-11011\"}]}"; // json转map
Map map = (Map) JSON.parse(jsonStr);
System.out.println("map的value类型:" + map.get("OPERATION").getClass());
JSONArray jsonArray = (JSONArray) map.get("OPERATION");
printMethod(jsonArray);
} /**
* @description json字符串转map
* @author AlphaJunS
* @date 2019/10/23
* @param []
* @return void
*/
@Test
public void run1() {
String jsonStr= "{\"OPERATION\":{\"ID\":\"SX5-1001432\",\"PROCESSID\":\"OP2080\"}}";
// json转map
Map map = (Map) JSON.parse(jsonStr);
System.out.println("map的value类型:" + map.get("OPERATION").getClass());
JSONObject jsonObject = (JSONObject) map.get("OPERATION");
System.out.println("ID:" + jsonObject.get("ID") + ",PROCESSID:" + jsonObject.get("PROCESSID"));
} /**
* @description 遍历json数组打印
* @author AlphaJunS
* @date 2019/10/23
* @param [jsonArray]
* @return void
*/
public void printMethod(JSONArray jsonArray) {
// 遍历json数组
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject jsonObject = (JSONObject) jsonArray.get(i);
System.out.println("第" + (i + 1) + "个对象:");
System.out.println("ID:" + jsonObject.get("ID") + ",PROCESSID:" + jsonObject.get("PROCESSID"));
}
}
}