JAVA中如何将一个json形式的字符串转为json对象或对象列表

  

import java.util.*;
import java.text.SimpleDateFormat; import org.json.JSONObject;
import org.json.JSONArray;
import org.json.JSONException; public class test_client { public static void test(){
//把json字符串转为json对象
String js ="{\"uniqueCode\":\"OTTCD015\",\"terminalBrandCode\":\"10\",\"equipmentBrand\":\"夏普\"}";
JSONObject jsonObj = new JSONObject(js);
System.out.println(jsonObj.get("uniqueCode")); //把json字符串列表转为json对象列表
String jslist ="[{\"uniqueCode\":\"OTTCD015\",\"terminalBrandCode\":\"10\",\"equipmentBrand\":\"夏普\"}," +
"{\"uniqueCode\":\"OTTCD016\",\"terminalBrandCode\":\"30\",\"equipmentBrand\":\"惠普\"}]";
JSONArray objar = new JSONArray(jslist);
List<Object> list = objar.toList();
for(Object obj :list){
// System.out.println(obj.toString());
Map<String,Object> map = (HashMap<String,Object>)obj;
Set<String> sets = map.keySet();
for(String key:sets){
System.out.println(key+": "+map.get(key));
}
System.out.println();
}
}

  输出:

    OTTCD015

    uniqueCode: OTTCD015
    terminalBrandCode: 10
    equipmentBrand: 夏普

    uniqueCode: OTTCD016
    terminalBrandCode: 30
    equipmentBrand: 惠普

上一篇:IT人学习方法论(一):学习方向


下一篇:[leetcode]349. Intersection of Two Arrays数组交集