首先导入json.jar,非常简单看过代码就明白怎么用了

package cn.mylucene;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class MyJson {
	public static void main(String[] args) throws JSONException {
       ParseJson("{\"name\":\"Alexia\",\"age\":\"23\"}");
       CreateJson();
	}
	
	//解析JSON
	private static void ParseJson(String jsonString) throws JSONException
	{
		JSONObject jObject = new JSONObject(jsonString);
        System.out.println(jObject.get("name"));  
	}
	
	//创建一个JSON
	private static void CreateJson() throws JSONException
	{
		 // 下面构造两个map、一个list和一个Employee对象
        Map<String, String> map1 = new HashMap<String, String>();
        map1.put("name", "Alexia");
        map1.put("sex", "female");
        map1.put("age", "23");

        Map<String, String> map2 = new HashMap<String, String>();
        map2.put("name", "Edward");
        map2.put("sex", "male");
        map2.put("age", "24");

        // 将Map转换为JSONArray数据
        JSONArray jArray = new JSONArray();
        jArray.put(map1);
        jArray.put(map2);
       //定义JSON
        JSONObject jObject=new JSONObject();
        jObject.put("List", jArray);
        jObject.put("Count","1200");
        
        System.out.println(jObject.toString());
	}
}

  

来源:中国建筑市场网

版权声明:本文为lb809663396原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/lb809663396/p/5865305.html