Java中Json用法


首先导入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());
	}
}

  


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM